@daysnap/utils
Version:
33 lines (31 loc) • 625 B
JavaScript
// src/throttle.ts
function throttleLeading(fn, ms) {
let pre = 0;
return function(...args) {
const now = Date.now();
if (now - pre >= ms) {
fn.apply(this, args);
pre = now;
}
};
}
function throttleTrailing(fn, ms) {
let timer = null;
return function(...args) {
if (timer) {
return;
}
timer = setTimeout(() => {
fn.apply(this, args);
timer = null;
}, ms);
};
}
function throttle(fn, ms, mode = "trailing") {
return mode === "leading" ? throttleLeading(fn, ms) : throttleTrailing(fn, ms);
}
export {
throttleLeading,
throttleTrailing,
throttle
};