js 函數節流和防抖
throttle 節流
事件觸發到結束後隻執行一次。
應用場景
- 觸發
事件的時候, 如滑鼠移動。mousemove
-
事件的情況, 如搜尋。keyup
-
事件的時候, 譬如滑鼠向下滾動停止時觸發加載資料。scroll
coding
方法1 防抖
// function resizehandler(fn, delay){
// clearTimeout(fn.timer);
// fn.timer = setTimeout(() => {
// fn();
// }, delay);
// }
// window.onresize = () => resizehandler(fn, 1000);
方法2 閉包 防抖
function resizehandler(fn, delay){
let timer = null;
return function() {
const context = this;
const args=arguments;
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(context,args);
}, delay);
}
}
window.onresize = resizehandler(fn, 1000);
debounce 防抖
事件出發後一定的事件内執行一次。
- window 變化觸發
事件是, 隻執行一次。resize
- 電話号碼輸入的驗證, 隻需停止輸入後進行一次。
function resizehandler(fn, delay, duration) {
let timer = null;
let beginTime = +new Date();
return function() {
const context = this;
const args = arguments;
const currentTime = +new Date();
timer && clearTimeout(timer);
if ((currentTime - beginTime) >= duration) {
fn.call(context, args);
beginTime = currentTime;
} else {
timer = setTimeout(() => {
fn.call(context, args)
}, delay);
}
}
}
window.onresize = resizehandler(fn, 1000, 1000);