mirror of
https://github.com/cheeaun/phanpy.git
synced 2025-02-15 12:36:30 +01:00
27 lines
560 B
JavaScript
27 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);
|
||
|
}
|
||
|
};
|
||
|
}
|