<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta name="author" content="杨欣"> <title>防抖与节流</title> <style> </style> </head> <body> <label for="debounce">测试防抖:</label> <input type="text" id="debounce"><br> <label for="ithrottlept">测试节流:</label> <input type="text" id="throttle"><br> <script> var input1 = document.getElementById("debounce"); var input2 = document.getElementById("throttle");
//防抖的含义就是让某个时间期限内,事件处理函数只执行一次。 function debounce(fn, wait) { var timeout; return function () { clearTimeout(timeout) var context = this, args = arguments; timeout = setTimeout(function () { fn.apply(context, args) }, wait) } } var handlerDebounce = debounce(function () { console.log("防抖成功!"); }, 500) input1.addEventListener("input", handlerDebounce)
//如果短时间内大量触发同一事件,那么在函数执行一次之后,该函数在指定的时间期限内不再工作,直至过了这段时间才重新生效。
function throttle(fn, wait) { var context, args, timer; return function () { if (!timer) { context = this, args = arguments; timer = setTimeout(function () { timer = null; fn.apply(context, args) }, wait); } } } var handlerThrottle = throttle(function () { console.log("节流成功"); }, 500) input2.addEventListener("input", handlerThrottle) </script> </body> </html>