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
事件是, 只執行一次。 - 電話號碼輸入的驗證, 只需停止輸入後進行一次。
coding
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);
Demo
CodePen-demo
參考文章
http://www.alloyteam.com/2012...