2020-02-26
描述
创建一个防止抖动的函数,使其延迟调用提供的函数,直到上次调用该函数至少经过了 ms 毫秒
提示
- 防止抖动函数每一次被调用前,都需要使用
clearTimeout()清空上一次将要运行的 timeout - 使用
setTimeout()创建一个新的 timeout,将调用的函数延迟至少ms后在执行 - 使用
Function.prototype.apply()设置函数的上下文为this,并提供必要的参数 - 第二个设置 timeout 的参数
ms的默认值为 0
代码
const debounce = (fn, ms = 0) => {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn.apply(this, args), ms);
};
};
示例
250 毫秒后打印最近一次窗口变化后的尺寸:
window.addEventListener(
'resize',
debounce(() => {
console.log(window.innerWidth);
console.log(window.innerHeight);
}, 250)
); // Will log the window dimensions at most every 250ms
ME!
链滴