@tmlmobilidade/utils
Version:
A collection of utility functions and helpers for the TML Mobilidade Go monorepo, providing common functionality for batching operations, caching, HTTP requests, object manipulation, permissions, and more.
38 lines (37 loc) • 1.19 kB
JavaScript
/* * */
import { TimeSlotMap } from '@tmlmobilidade/dates';
/**
* Runs an asynchronous function at regular intervals, ensuring that each invocation
* completes before the next one starts. Errors are logged and can optionally be re-thrown.
*/
export async function runOnInterval(fn, options) {
//
//
// Validate and determine the interval in milliseconds,
// or throw an error if the provided interval is invalid.
let intervalMs;
if (typeof options.intervalMs === 'number')
intervalMs = options.intervalMs;
else if (!TimeSlotMap[options.intervalMs])
throw new Error(`Invalid TimeSlot: ${options.intervalMs}`);
else
intervalMs = TimeSlotMap[options.intervalMs];
//
// Define the runner function that will execute
// the provided function and schedule the next execution.
const runner = async () => {
try {
await fn();
}
catch (error) {
console.error('Error in runOnInterval:', error);
if (options.throwOnError)
throw error;
}
finally {
setTimeout(runner, intervalMs);
}
};
await runner();
//
}