JavaScript Concurrency: clearTimeout
Welcome to the clearTimeout 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 that
setTimeoutschedules a function to run in the future. But what if we want to cancel a timer that we've already created? Fortunately, we can do that with theclearTimeoutfunction.In browsers,
setTimeoutalways returns a number, which is the ID of the timer. NodeJS behaves a bit differently: there,setTimeoutreturns an object. In both cases, we can passsetTimeout's return value toclearTimeout, which will cancel the timer. We just have to remember to storesetTimeout's return value in a variable.>
const array = [];const timer = setTimeout(() => { array.push('timer'); }, 1000);clearTimeout(timer);array;Async Result:
[]
>
const array = [];const timer1 = setTimeout(() => { array.push('timer 1'); }, 1000);const timer2 = setTimeout(() => { array.push('timer 2'); }, 1000);clearTimeout(timer2);array;Async Result:
['timer 1']
What if we call
clearTimeouton a timer that was already cleared, or a timer that already finished? In both cases, there's nothing to clear. Trying to clear the timer does nothing.>
const array = [];const timer1 = setTimeout(() => { array.push('timer 1'); }, 1000);const timer2 = setTimeout(() => { array.push('timer 2'); }, 1000);clearTimeout(timer2);clearTimeout(timer2);array;Async Result:
['timer 1']
clearTimeoutdoesn't mind if we pass in something that's not a timer. For example, calling it withundefinedwon't throw an exception.>
clearTimeout(['not', 'a', 'timer']);clearTimeout(undefined);Result:
Here's a code problem:
Clear the timer to prevent it from running.
const array = [];const timer = setTimeout(() => { array.push('it ran'); }, 100);clearTimeout(timer);array;Async Result:
- Goal:
[]
- Yours:
[]
Canceling timers is relatively uncommon, but it eventually comes up in most production applications. Here's an example.
Imagine that we're building a client-side web application in a security-sensitive industry like banking. We need to log the user out automatically after five minutes of inactivity. Every time the user takes an action, like clicking a button or typing into a text box, we want to restart the five-minute inactivity countdown. (Being occasionally logged out is annoying to users, but it also reduces the chance of someone leaving their account logged in on a public computer!)
Here's some code expressing that idea. We won't actually run this code; it's just a sketch of a solution.
>
const inactivity = {timer: undefined,reset() {clearTimeout(this.timer);const fiveMinutes = 5 * 60 * 1000;this.timer = setTimeout(logOut, fiveMinutes);}};inactivity.reset();clearTimeoutmakes that code relatively simple. We just need to provide alogOutfunction, and we need to modify our application to callinactivity.reset()whenever the user clicks a button, etc.Now our users are slightly annoyed, but some are safer!