美文网首页
防抖函数的两种实现方式

防抖函数的两种实现方式

作者: 小漠穷秋 | 来源:发表于2018-04-27 18:01 被阅读0次

防抖主要为了防止事件在短期内反复执行。一般有如下两种方式:
1.自杀模式
2.clearTimeout模式

调用方法window.onresize = throttle(fn,wait);
function fn(){
console.log('test');
}
wait = 1000;

1.自杀模式
第一次直接运行,不存在延时
function throttle(fn,wait) {
var timer;
return function(){
if(!timer) {
timer = setTimeout(function(){
timer = null;
},wait);
fn.apply(this);
}
}
}

2.clearTimeout方式
第一次执行存在延时
function throttle(fn,timer) { //防抖函数
console.log(timeout);
var timeout = null;
return function() { //使用闭包 一个闭包
if (timeout != null) {
console.log(timeout);
clearTimeout(timeout);
}
timeout = setTimeout(fn,timer);
}
}

相关文章

网友评论

      本文标题:防抖函数的两种实现方式

      本文链接:https://www.haomeiwen.com/subject/iiavmxtx.html