1、概念瀏覽器
// 簡單的防抖函數 function debounce(func, wait){ var timeout; return function() { clearTimeout(timeout); // 清除計時器 timeout = setTimeout(func, wait); }; }; // 實際想要請求的函數 function realFun(){ console.log('success'); } // 採用防抖 window.addEventListener('scroll', debounce(realFun, 500)); // 沒有采用防抖動 window.addEventListener('scroll', realFunc);
// 節流函數 function throttle(func, wait, mustRun){ var timeout, startTime = new Date(); return function(){ var context = this; // 其實這裏的this指的是window var curTime = new Date(); clearTimeout(timeout); if(curTime - startTime >= mustRun){ func.apply(context); startTime = curTime; }else { timeout = setTimeout(func, wait); } }; }; // 要出發的事件handler function realFunc(){ console.log('success'); } // 採用節流函數 window.addEventListener('scroll', throttle(realFunc, 500, 1000));