Skip to content

Scheduler

runtoolkit edited this page Apr 13, 2026 · 1 revision

Scheduler

Delayed and repeated execution, debounce, throttle, and one-time guards.

Constructor

import { Scheduler } from './src/scheduler.js';

const s = new Scheduler();

schedule / cancel

// Run once after 1000ms
s.schedule('key', fn, 1000);

// Run after 1000ms, then repeat every 2000ms
s.schedule('key', fn, 1000, 2000);

// Shorthand: run immediately, then repeat every 500ms
s.scheduleEvery('key', fn, 500);

// Cancel
s.cancel('key');    // → true if found and cancelled
s.cancelAll();      // cancel everything

s.list();           // → ['key', ...]

Scheduling the same key again cancels the previous entry automatically.


repeat

Runs fn exactly n times, spaced by interval ms. Returns a cancel function.

const cancel = s.repeat((i) => {
  console.log('step', i); // i is 0-indexed
}, 5, 500);

cancel(); // stop early

wait

Returns a Promise that resolves after ms milliseconds.

await s.wait(1000);

debounce / throttle

const debounced = s.debounce(fn, 300);
// fn fires 300ms after the last call

const throttled = s.throttle(fn, 100);
// fn fires at most once per 100ms

Both return wrapped functions. The originals are not modified.


once / resetOnce

Runs fn the first time once(key) is called. Subsequent calls with the same key are no-ops.

s.once('init', () => console.log('only once')); // → true (ran)
s.once('init', () => console.log('ignored'));   // → false (skipped)

s.resetOnce('init'); // allows it to fire again

tickGuard / clearTickGuard

Scoped one-time guard combining a key and a tick ID. Useful for ensuring something runs at most once per tick.

s.tickGuard('my_action', tickId, () => {
  // runs once per unique (key, tickId) pair
});

s.clearTickGuard('my_action'); // clears all guards for this key

Error handling

Errors inside schedule, repeat, and once callbacks are caught and logged to console.error. They do not cancel the schedule.

Clone this wiki locally