Skip to content

Instantly share code, notes, and snippets.

@romelperez
Created February 26, 2022 04:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romelperez/28ad163b6c9f7888b9dace530a190621 to your computer and use it in GitHub Desktop.
Save romelperez/28ad163b6c9f7888b9dace530a190621 to your computer and use it in GitHub Desktop.
Timeout Task Scheduler
import { isBrowser } from './browser';
type TOSchedulerId = number | string;
type TOSchedulerCallback = () => unknown;
const timeoutTask = (delay: number, callback: TOSchedulerCallback): () => void => {
const scheduleId = setTimeout(() => callback(), delay);
return () => clearTimeout(scheduleId);
};
declare function TOSchedulerStart (id: TOSchedulerId, time: number, callback: TOSchedulerCallback): void;
declare function TOSchedulerStart (time: number, callback: TOSchedulerCallback): void;
interface TOScheduler {
stop: (id: TOSchedulerId) => void
stopAll: () => void
start: typeof TOSchedulerStart
isPending: (id?: TOSchedulerId) => boolean
}
function createTOScheduler (): TOScheduler {
const timeouts: Record<TOSchedulerId, TOSchedulerCallback> = {};
const clean = (id: TOSchedulerId): void => {
delete timeouts[id]; // eslint-disable-line @typescript-eslint/no-dynamic-delete
};
const stop = (id: TOSchedulerId): void => {
timeouts[id]?.();
clean(id);
};
const stopAll = (): void => {
Object.keys(timeouts).forEach(stop);
};
const start = (a: TOSchedulerId | number, b: TOSchedulerCallback | number, c?: TOSchedulerCallback): void => {
if (!isBrowser) {
return;
}
const id = c ? a : '';
const time = (c ? b : a) as number;
const callback: () => unknown = c || b as TOSchedulerCallback;
stop(id);
timeouts[id] = timeoutTask(time, () => {
clean(id);
callback();
});
};
const isPending = (id?: TOSchedulerId): boolean => {
return timeouts[id ?? ''] !== undefined;
};
return Object.freeze({ stop, stopAll, start, isPending });
}
export type { TOScheduler };
export { createTOScheduler };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment