js 函数节流和防抖

5次阅读

共计 1007 个字符,预计需要花费 3 分钟才能阅读完成。

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);
DemoCodePen-demo
参考文章 http://www.alloyteam.com/2012…

正文完
 0