phanpy/src/utils/ratelimit.js
Lim Chee Aun 49fd8a5dc9 Further rate limit this threadify calls
Every post calls threadify and clogs the RAF
2023-12-22 09:54:50 +08:00

26 lines
560 B
JavaScript

// Rate limit repeated function calls and queue them to set interval
export default function rateLimit(fn, interval) {
let queue = [];
let isRunning = false;
function executeNext() {
if (queue.length === 0) {
isRunning = false;
return;
}
const nextFn = queue.shift();
nextFn();
setTimeout(executeNext, interval);
}
return function (...args) {
const callFn = () => fn.apply(this, args);
queue.push(callFn);
if (!isRunning) {
isRunning = true;
setTimeout(executeNext, interval);
}
};
}