11.3. A cancellable timeout and interval
Topics
This question is in
11. TimersEvery timer needs a way to stop it: a toast that is dismissed before it hides itself, a polling loop that ends when the user leaves the page, a component that is removed while its timer is still waiting. The built-ins hand back an id, and you have to keep it and pass it to the right clear function. Many codebases wrap that in a helper that returns a cancel function instead: the caller does not need to know which timer is underneath, and "stop this" is one call.
Write timeout(fn, delay, ...args) and interval(fn, delay, ...args) in cancellable.js. Each starts its timer at once and returns a cancel function.
Signature
function timeout(fn, delay, ...args) // returns cancel()
function interval(fn, delay, ...args) // returns cancel()fn: the function to run, called withargs.delay: milliseconds.cancel()takes no arguments and returnstrueif it stopped something that was still going,falseif there was nothing left to stop.
Requirements
timeout
fn(...args)runs once, exactlydelayms after the call, never during the call (even withdelay0).cancel()before it runs stops it for good:fnnever runs and no timer is left waiting. It returnstrue.cancel()afterfnhas run, or a secondcancel(), does nothing and returnsfalse.
interval
fn(...args)runs everydelayms: atdelay,2 × delay,3 × delay…, with the same arguments each time.cancel()stops it: no more runs and no timer left waiting. The first call returnstrue, every later callfalse.cancel()works from insidefn: the current run finishes, and there is no next one.cancel()before the first run meansfnnever runs.
both
- Every call has its own timer and its own
cancel: canceling one never affects another.
Examples
const cancel = timeout(console.log, 1000, "hello");
cancel(); // true: "hello" is never printed
cancel(); // false: nothing left to stoplet ticks = 0;
const stop = interval(() => {
ticks += 1;
if (ticks === 3) stop(); // stops itself after the third run
}, 500);
// runs at 500, 1000 and 1500 ms, then never againconst cancel = timeout(() => console.log("done"), 0);
// later, after "done" was printed:
cancel(); // false: it already ranEnvironment
- Plain JavaScript in a browser page; the tests call the globals
timeoutandintervalfromcancellable.js. - The tests run on a virtual clock that replaces
setTimeout,setIntervaland their clear functions; use those. - What
fnreturns is not used.fnthrowing is not part of this problem.
Hints
- Where does the timer id live so that
cancelcan still reach it aftertimeouthas returned? - How does
cancelknow whether the timeout already ran?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it