A slideshow advances every 5 seconds and pauses while the pointer is over it. A game ticks every second and stops while the menu is open. With a plain setInterval, pausing means clearing it, and resuming means starting a new one, which waits a full period again: pause 4 seconds into a 5-second slide, resume, and the slide stays up for 9 seconds. A pausable interval remembers how much of the wait was left.
Write createPausableInterval(fn, delay) in pausable-interval.js. It starts at once and returns three controls: pause, resume and stop.
It starts straight away: fn runs at delay, 2 × delay, 3 × delay… after the call, never earlier. fn receives the run number, which keeps counting across pauses.
pause() stops the runs and remembers how much of the current wait was left. While paused, fn never runs and no timer is waiting.
resume() waits only for the time that was left, runs fn, and then goes back to running every delay ms. Paused right after a run, the next run comes a full delay after resume().
pause() while already paused does nothing (the time left stays what it was at the first pause). resume() while running does nothing (no extra runs, no change to the schedule).
stop() ends it for good: no more runs, no timer left, and a later resume() does nothing. It works while running and while paused.
pause() and stop() work from inside fn.
At most one timer is ever waiting.
Each pausable interval is independent of the others.
constslides=createPausableInterval((n) => console.log("slide", n), 1000);// 1000 ms: slide 1// 1400 ms: slides.pause() (600 ms of the wait were left)// 5000 ms: slides.resume()// 5600 ms: slide 2 (only the 600 ms that were left)// 6600 ms: slide 3 (a full 1000 ms again)
JAVASCRIPT
constticker=createPausableInterval((n) => {if (n ===3) ticker.stop();}, 200);// runs at 200, 400 and 600 ms, then never again
JAVASCRIPT
consta=createPausableInterval(console.log, 100);a.resume(); // does nothing: it is not pauseda.pause();a.pause(); // does nothing: already paused
Plain JavaScript in a browser page; the tests call the global createPausableInterval from pausable-interval.js.
The tests run on a virtual clock that replaces setTimeout, setInterval, their clear functions, Date.now and performance.now; use those to schedule and to measure time.