節流函數其主要做用就是防止用戶在短期內屢次觸發該事件。html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body><script> function throttle(fn, delay, duration) { var timer = null, begin = new Date(); return function() { var context = this, args = arguments, current = new Date(); clearTimeout(timer); if (current - begin >= duration) { fn.apply(context, args); begin = current; } else { timer = setTimeout(function() { fn.apply(context, args); }, delay) } } }; function demo() { console.log(1) } /*參數說明:第一個參數是要執行的函數,第二個參數是說在500毫秒內連續觸發了該函數只執行一次,第三個參數是說每隔200毫秒自動執行一次該函數*/ window.onresize = throttle(demo, 500, 200) </script> </body> </html>
簡單高效的方法:app
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <script> function throttle(method, context) { clearTimeout(method.tId); method.tId = setTimeout(function() { method.call(context); }, 300); }; function demo() { console.log(1) } window.onresize = function(){
throttle(demo, window)
} </script> </body> </html>