Interval ticker that resumes with the remaining time
A workout app shows one exercise every 30 seconds. When the user taps pause 20 seconds into an exercise and resumes a minute later, the next exercise should appear after the remaining 10 seconds, not after a fresh 30. A plain setInterval cannot do that: clearing and restarting it always starts a full period again.
Implement createTicker(callback, period). It returns a ticker object that calls callback every period milliseconds while it is running, and that can be paused, resumed and stopped.
const ticker = createTicker(callback, period);
ticker.start(); // start, or resume after a pause
ticker.pause(); // pause, remembering how much of the current period is left
ticker.stop(); // stop for good
ticker.getState(); // => 'idle' | 'running' | 'paused' | 'stopped'
'idle'. Nothing is scheduled until start() is called.start() from 'idle': the state becomes 'running', the first tick happens period ms later, and the next ticks every period ms after that.pause() while 'running': cancel the pending tick and remember the time left until it. The state becomes 'paused'.start() from 'paused': the state becomes 'running', the next tick happens after the remembered time left, and then every period ms again. Pausing and resuming several times within one period keeps adding up correctly.stop() from any state: cancel the pending tick. The state becomes 'stopped', and the ticker never ticks again.start() while running or after stopping, and pause() when not running. A ticker never has more than one tick scheduled.callback receives the tick number, starting at 1. The count continues across pauses.pause() or stop() on its own ticker. Pausing inside the callback leaves a full period for the next tick.period is a positive number of milliseconds. Each ticker is independent.const ticker = createTicker((n) => console.log('exercise', n), 100);
ticker.start();
// t=100 exercise 1
// t=200 exercise 2
// t=230 ticker.pause() (70ms of the period are left)
// t=900 ticker.start()
// t=970 exercise 3
// t=1070 exercise 4
ticker.stop();
ticker.start(); // ignored, the ticker stays 'stopped'
The tests replace setTimeout, clearTimeout, setInterval, clearInterval and performance.now() with a fake clock. Use those global functions (looked up when you need them, not saved at load time) and measure elapsed time with performance.now(), not Date.now().