js:防抖动与节流【转载】
源文:https://blog.****.net/crystal6918/article/details/62236730#reply
<!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"> <title>Document</title> </head> <body> <div > <div style="height: 3000px;background: yellow;"></div> </div> </body> <script> //初级防抖 /* // 将会包装事件的 debounce 函数 function debounce(fn, delay) { // 维护一个 timer let timer = null; return function () { // 通过 ‘this’ 和 ‘arguments’ 获取函数的作用域和变量 let context = this; let args = arguments; clearTimeout(timer); timer = setTimeout(function () { fn.apply(context, args); }, delay); } } // 当用户滚动时被调用的函数 function foo() { console.log('You are scrolling!'); } // 在 debounce 中包装我们的函数,过 2 秒触发一次 let elem = document.getElementById('container'); elem.addEventListener('scroll', debounce(foo, 500)); */ //更高级防抖 /* function debounce(func, delay, immediate) { var timer = null; return function () { var context = this; var args = arguments; if (timer) clearTimeout(timer); if (immediate) { //根据距离上次触发操作的时间是否到达delay来决定是否要现在执行函数 var doNow = !timer; //每一次都重新设置timer,就是要保证每一次执行的至少delay秒后才可以执行 timer = setTimeout(function () { timer = null; }, delay); //立即执行 if (doNow) { func.apply(context, args); } } else { timer = setTimeout(function () { func.apply(context, args); }, delay); } } } function foo() { console.log('You are scrolling!'); } let elem = document.getElementById('container'); elem.addEventListener('scroll', debounce(foo, 500, true)); */ </script> <script> //节流1.时间戳版 /* var throttle = function(func,delay){ var prev = Date.now(); return function(){ var context = this; var args = arguments; var now = Date.now(); if(now-prev>=delay){ //func() func.apply(context,args); prev = Date.now(); } } } */ //节流2.定时器版 /* var throttle = function (func, delay) { var timer = null; return function () { var context = this; var args = arguments; if (!timer) { timer = setTimeout(function () { func.apply(context, args); timer = null; }, delay); } } } */ //节流3.综合使用时间戳与定时器 var throttle = function (func, delay) { var timer = null; var startTime = Date.now(); return function () { var curTime = Date.now(); var remaining = delay - (curTime - startTime); var context = this; var args = arguments; clearTimeout(timer); if (remaining <= 0) { func.apply(context, args); startTime = Date.now(); } else { timer = setTimeout(func, remaining); } } } function foo() { console.log('arguments'); } let elem = document.getElementById('container'); elem.addEventListener('scroll', throttle(foo, 500, true)); </script> </html>