在触发一段时间后执行事件,如果这段时间内又触发了,则继续等待同样的时间。
防抖在实际开发中使用场景还是蛮多,比如列表的实时搜索等。延时执行,这很容易想到使用setTimeout来实现。
基础版
function debounce(func, wait) { let timer; return function () { timer && clearTimeout(timer); timer = setTimeout(func, wait); };}
测试一下
// 使用input输入框做一个测试// html
嗯。好像没什么问题。不过我们发现上面在获取input的值的时候使用的是input.value,那其实oninput事件应该是存在一个参数是event,可以直接使用event.target.value获取。
// 使用input输入框做一个测试// html
不出意料的报错了,这是因为debounce函数返回的是一个新的函数,并没有将原有函数的this值绑定到新的函数上,也没有将参数传递给新的函数。我们来改一改。
处理了this和参数的版本
function debounce(func, wait) { let timer; return function (...args) { timer && clearTimeout(timer); timer = setTimeout(() => { func.apply(this, args); }, wait); };}
这时候又来了个新需求,需要在计时开始时执行,而不是在结尾执行。同样的,原来的逻辑不变,只是需要新增一个立即执行的逻辑。想一想我们的需求:立即执行,然后在固定的一段时间内不再触发第二次 。在立即执行代码之后,可以设置一个变量flag(初始值为true)用来记录上一次执行的时间到现在是否超过wait,如果超过则将flag设置为true,意味着可以再次执行。
function debounce(func, wait, immediate) { let timer; return function (...args) { timer && clearTimeout(timer); if (immediate) { // timer就是我们使用的flag if (!timer) { func.apply(this, args); } // 在代码执行的wait s之后将timer设置为null // 当下一次执行当前函数则可以触发判断 !timer === true timer = setTimeout(() => { timer = null; }, wait); } else { timer = setTimeout(() => { func.apply(this, args); }, wait); } };}
当然,我们还可以像lodash一样,添加cancel、pending等方法。
function debounce(func, wait, immediate) { let timer; const debounced = function (...args) { timer && clearTimeout(timer); if (immediate) { if (!timer) { func.apply(this, args); } timer = setTimeout(() => { timer = null; }, wait); } else { timer = setTimeout(() => { func.apply(this, args); timer = null; }, wait); } }; debounced.cancel = function() { timer && clearTimeout(timer); } debounced.pending = function() { return !!timer; } return debounced;}
文章来源:https://segmentfault.com/newest
最后
刚整理 2020 年全套最新精品技术资料免费发给你! (原价最少8999元,超2000G!)
领取 看看下面!!
1、点赞 + 评论 (勾选 “转发” )
2、关注小编私信。点击头像,关注。并私信回复关键词: 1024