一、封装防抖函数
debounce(fn, time) {
let timer = null;
return function(...args) {
let _this = this;
if(timer) {
clearTimeout(timer);
}
timerv = setTimeout(() => {
fn.apply(_this, args);
}, time)
}
}
二、在函数中进行调用
this.debounce(() => {
console.log('hello world');
}, 1000)();
三、注意点
当调用debounce函数后,为了使其能够更快的执行相关的函数,需要让其立即进行执行。因为debounce函数返回的是一个函数,其是一个闭包,为了使debounce函数中所传递的函数能够进行执行,需要立即执行它,即执行它所返回的函数。