@augment-vir/common
Version:
A collection of augments, helpers types, functions, and classes for any JavaScript environment.
31 lines (30 loc) • 921 B
JavaScript
import { convertDuration } from '@date-vir/duration';
/**
* Creates an interval that prevents multiple parallel executions. If the previous callback
* execution is still executing, the next one will not fire.
*
* @category Interval
* @category Package : @augment-vir/common
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common)
*/
export function createBlockingInterval(callback, interval) {
let isExecuting = false;
const intervalId = globalThis.setInterval(async () => {
if (isExecuting) {
return;
}
isExecuting = true;
try {
await callback();
}
finally {
isExecuting = false;
}
}, convertDuration(interval, { milliseconds: true }).milliseconds);
return {
intervalId,
clearInterval() {
globalThis.clearInterval(intervalId);
},
};
}