实现说明
底层就是函数 debounce、debounced。
TypeError、RangeError 之前有一道守卫:坏状态在这里就停下,不会继续往下走。
使用要点
- 守卫
typeof fn !== "function"成立时借助提前的throw直接离开。 - 把
debounce当作 API:导入它,其余代码可以忽略。
常见问题
遇到格式错误的数据会怎样?
代码会拒绝继续:抛出 TypeError、RangeError,此时状态仍可恢复。
在一个没有任何依赖声明的空项目里能跑吗?
可以——空项目原样能跑,因为什么都不用声明。 文件在加载时定义 debounce、debounced。
签名一览:export function debounce(fn, waitMs)
核心语句
if (typeof fn !== "function") throw new TypeError("fn must be a function");
if (waitMs < 0) throw new RangeError("waitMs must be >= 0");
return function debounced(...args) {
lastArgs = args;
if (timer !== null) clearTimeout(timer);
timer = setTimeout(() => {
timer = null;
fn.apply(this, lastArgs);
}, waitMs);
};
代码示例
export function debounce(fn, waitMs) {
if (typeof fn !== "function") throw new TypeError("fn must be a function");
if (waitMs < 0) throw new RangeError("waitMs must be >= 0");
let timer = null;
let lastArgs = null;
return function debounced(...args) {
lastArgs = args;
if (timer !== null) clearTimeout(timer);
timer = setTimeout(() => {
timer = null;
fn.apply(this, lastArgs);
}, waitMs);
};
}