This commit is contained in:
Mrhongxing committed 2026-11-12 02:48:46 +08:00
1 parent d1ee8edbbd
commit 7733a44362
429 files changed
+75840 -94

No files matched your search

+45
View File
@@ -0,0 +1,45 @@
/**
* Throttle decorator
* @param {Function} fn
* @param {Number} freq
* @return {Array<Function>}
*/
function throttle(fn, freq) {
let timestamp = 0;
let threshold = 1000 / freq;
let lastArgs;
let timer;
const invoke = (args, now = Date.now()) => {
timestamp = now;
lastArgs = null;
if (timer) {
clearTimeout(timer);
timer = null;
}
fn(...args);
};
const throttled = (...args) => {
const now = Date.now();
const passed = now - timestamp;
if (passed >= threshold) {
invoke(args, now);
} else {
lastArgs = args;
if (!timer) {
timer = setTimeout(() => {
timer = null;
invoke(lastArgs);
}, threshold - passed);
}
}
};
const flush = () => lastArgs && invoke(lastArgs);
const flushWith = (...args) => invoke(args);
return [throttled, flush, flushWith];
}
export default throttle;