Asynchronous: Timers

Event handlers are just one possible use case for callbacks.

Another quite useful one are timers.

One thing to note is that just like event handlers, timers are not part of the JavaScript language. They are add-ons, provided by the browser or Node.js depending if you write frontend or backend code.

But I mention them because they are perfect to explain callbacks and asynchronous code.

We have 2 kinds of timers:

  • setTimeout()
  • setInterval()

With setTimeout you specify a callback function to execute later, and a value expressing how later you want it to run, in milliseconds:

setTimeout(() => {
  // runs after 2 seconds
}, 2000)

setTimeout(() => {
  // runs after 50 milliseconds
}, 50)

setTimeout returns the timer id. This is generally not used, but you can store this id, and clear it if you want to delete this scheduled function execution:

const id = setTimeout(() => {
  // should run after 2 seconds
}, 2000)

// I changed my mind
clearTimeout(id)

setInterval() is a function similar to setTimeout, with a difference: instead of running the callback function once, it will run it forever, at the specific time interval you specify (in milliseconds):

setInterval(() => {
  // runs every 2 seconds
}, 2000)

The function above runs every 2 seconds unless you tell it to stop, using clearInterval, passing it the interval id that setInterval returned:

const id = setInterval(() => {
  // runs every 2 seconds
}, 2000)

clearInterval(id)

It’s useful to call clearInterval inside the setInterval callback function, to let it auto-determine if it should run again or stop. For example, this code runs something unless status has the value done:

const interval = setInterval(() => {
  if (status === 'done') {
    clearInterval(interval)
    return
  }
  // otherwise do things
}, 100)

Lessons in this unit:

0: Introduction
1: Callbacks
2: ▶︎ Timers
3: Promises
4: Async functions
5: Chaining promises
6: Orchestrating promises
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. Launching May 21, 2024. Join the waiting list!