跳到主要内容

防抖

防抖

基本的防抖函数的作用是,在调用一个防抖函数之后,函数的调用只会在指定的时间之后调用。也就是说,指定的时间内调用若干次防抖函数,只会有最后一次调用生效,并且最后一次调用生效的时间在指定的时间之后。

下面是最原始的防抖函数,还没有进行一些细节的修改。

其中实现了一个 sleep 函数,然后将所有函数的调用都在一个 IIFE 中来进行,方便 await 来阻塞调用栈,达到 sleep 睡眠的效果。

function debounce(func, wait) {
let timer = null;

return () => {
if (timer) {
clearTimeout(timer);
timer = null;
}

timer = setTimeout(() => {
func();
}, wait);
};
}

const sleep = (ms) =>
new Promise((resolve) => {
setTimeout(() => {
resolve();
}, ms);
});

const debounceTest = debounce(() => {
console.log("debounce");
}, 200);

(async () => {
debounceTest();
debounceTest();
debounceTest();
await sleep(200);
debounceTest();
})();

接下来会对防抖函数的细节进行一些补充

参数的传递

现在要实现的是参数的传递,也就是在debounceEnhanced函数被创建之后,调用debounceEnhanced函数的时候传入的参数能够被传入到debounceEnhanced的回调函数的 params 去。当然,需要使用 this 的情况下,可以用 func.apply(this,args)来在函数调用的时候进行参数的传递以及 this 的绑定。

function debounceEnhanced(func, wait) {
let timer = null;

- return () => {
+ return (...args) => {
if (timer) {
clearTimeout(timer);
timer = null;
}

timer = setTimeout(() => {
- func();
+ func(...args);
}, wait);
};
}

const debounceEnhancedTest = debounceEnhanced((args) => {
console.log(args);
}, 200);

debounceEnhancedTest("test");