实现debounce
思路:通过setTimeout
实现,如果之前存在timer,则先清空之前的timer,再调用方法。
这里需要注意的是,因为回调函数的this会默认指向window,如果不提前保存下来,则会在对象调用时丢失this。这里有两种处理方法:
- 如果setTimeout里面的回调函数是通过匿名函数形式
function(){}
写的,则此时的this是在调用时才绑定,所以需要提前保存。 - 如果setTimeout里面的回调函数是通过箭头函数形式
()=>{}
写的,则此时的this是在箭头函数创建时被绑定的,所以可以直接在箭头函数里传入this。
export default function debounce(func, wait = 0) {
let timer = null;
return function (...args) {
const context = this; // 保存调用的this
clearTimeout(timer);
timer = setTimeout(function () {
timer = null; // 不必要,因为clearTimeout如果传入不存在的id也不会抛出异常
func.apply(context, args);
}, wait);
};
}
function debounce(func, wait) {
let timer = null
return function(...args){
clearTimeout(timer)
timer = setTimeout(()=>{
timer = null
func.apply(this, args) // 直接传入this
}, wait)
}
}