JavaScript Concurrency: setInterval and clearInterval
Welcome to the setInterval and clearInterval lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
We've seen
setTimeout, which calls a function one time after a delay. ThesetIntervalfunction is similar. Just likesetTimeout, we passsetIntervala function and a delay in milliseconds.setTimeoutexecutes the function once at the end of the delay period (after any other running code is executed).setIntervalcalls the function repeatedly, waiting for the specified delay each time.We've also seen
clearTimeout, which cancels a timer. Intervals have an equivalent function,clearInterval. When we call it, the interval stops repeating.>
const array = [];// Start the interval, running every 1000 ms.const interval = setInterval(() => array.push('ran'), 1000);// Stop the interval after 2500 ms (after 2 runs)setTimeout(() => clearInterval(interval), 2500);array;Async Result:
['ran', 'ran']
If we set an interval and immediately clear it, it never runs.
>
const array = [];const interval = setInterval(() => array.push('ran'), 1);clearInterval(interval);array;Async Result:
[]
Finally, just as with
setTimeout, clearing something that's not an interval fails silently.>
clearInterval(['not a timer']);Result:
setIntervalis simple, but there's one pitfall to watch out for. If we don't provide a delay, it will default to 0, which means "run this interval as fast as you can".Here's an experiment: we create an interval with a delay of 0, then count how many times it runs in one second. (Unlike most examples, we won't actually run this one in your browser. The result varies unpredictably with each run, so we've hard-coded it.)
>
let result = {iterations: 0};const interval = setInterval(() => {result.iterations += 1;});setTimeout(() => {clearInterval(interval);}, 1000);result;Async Result:
It's important to watch out for this kind of runaway repetition when writing asynchronous code. The system may still work with this mistake in place, but it can be a big performance problem.