setTimeout & setInterval — JavaScript

setTimeout(fn, ms) runs the function fn once after ms milliseconds, and setInterval(fn, ms) runs it every ms milliseconds. Both return an id, the timer's…

A "Saved" notice appears, then disappears by itself three seconds later. A flash-sale countdown goes down every second. Both need code that runs later, not now.

The tool for that is a timer. There are two: setTimeout runs a function once after a delay, and setInterval runs it again and again with the same delay between runs. You write the delay in milliseconds (ms): 1000 ms is 1 second.

Scheduling code with setTimeout

This example prints three texts to the console. One of them is scheduled with setTimeout:

console.log('Start')

const id = setTimeout(() => {
  console.log('Done!')
}, 2000)

console.log('Waiting...')

The console shows Start, Waiting..., and then, 2 seconds later, Done!.

The code after a timer doesn't wait

setTimeout only schedules the callback. Then JavaScript continues with the next line right away. That is why Waiting... appears before Done!. The order stays the same even with a delay of 0:

console.log('A')
setTimeout(() => console.log('B'), 0)
console.log('C')

This prints A, C, then B. So the first thing printed is still A. A delay of 0 means "as soon as the code running now has finished", not "right now". The callback waits in a queue first, and only gets its turn once all the plain code has finished.

Repeating with setInterval, stopping with clearInterval

This example counts to 3, one number per second, then stops by itself:

let seconds = 0

const id = setInterval(() => {
  seconds++
  console.log(`Second ${seconds}`)
  if (seconds === 3) {
    clearInterval(id)
    console.log('Stopped!')
  }
}, 1000)

The result is Second 1, Second 2, Second 3, one line per second. Right after Second 3 comes Stopped!. A setTimeout timer can also be cancelled before it runs, with clearTimeout(id). If you write const id = setTimeout(...) and then clearTimeout(id), the callback never runs.

Waiting through a Promise

setTimeout does not return what its callback returns, only an id. When you need a function that finishes later and brings a value with it, wrap the timer in a Promise:

function wait(ms, value) {
  return new Promise((resolve) => {
    setTimeout(() => resolve(value), ms)
  })
}

wait(1000, 'Ready').then((result) => console.log(result))

After 1 second, the console prints Ready. Inside an async function you can also write const result = await wait(1000, 'Ready').

A countdown as an array

The setInterval example above prints one number per second. When all you need is a countdown list at once, in one array, use a for loop that counts down:

const numbers = []
for (let i = 3; i >= 0; i--) {
  numbers.push(i)
}
console.log(numbers) // [3, 2, 1, 0]

let i = 3 starts at the top number. i >= 0 includes 0 as well (with i > 0, the 0 is left out). i-- subtracts 1 on every round.

⚠️ Timers you can't stop, or that fire too soon

For a sale countdown, calculate the time left from the computer's clock each time the timer runs. Date.now() gives the current time in milliseconds:

const end = Date.now() + 10 * 1000 // 10 seconds from now

const id = setInterval(() => {
  const left = Math.max(0, end - Date.now())
  console.log(`${Math.ceil(left / 1000)} seconds left`)
  if (left === 0) clearInterval(id)
}, 1000)

Math.max(0, ...) keeps the time left from going below 0, and Math.ceil rounds up (8.4 becomes 9). It prints 9 seconds left down to 0 seconds left. Even when one pass is late, the number shown is still right, because it is calculated again from the clock.

TL;DR: setTimeout(fn, ms) runs the function fn once after ms milliseconds, and setInterval(fn, ms) runs it every ms milliseconds. Both return an id, the timer's number. clearTimeout(id) or clearInterval(id) stops the timer with that id. The code after a timer doesn't wait, not even with a delay of 0. Need a value after a delay? Make a new Promise, then call resolve(value) inside the setTimeout callback.

⚡ Scheduled now, runs later

Write:

console.log('Start')

setTimeout(() => {
  console.log('Done!')
}, 2000)

console.log('Waiting...')

Meaning: setTimeout schedules a function (a callback) to run once after a delay. Then JavaScript continues with the next line right away. So Waiting... appears before Done!. The delay is in milliseconds: 2000 is 2 seconds, and 2 is only 2 milliseconds.

⚡ A delay of 0 isn't right now

Write:

console.log('A')
setTimeout(() => console.log('B'), 0)
console.log('C')
Guess first: in what order do the letters print?

A, C, then B. The setTimeout callback waits in a queue first, even with a delay of 0.

Meaning: A delay of 0 means as soon as the code running now has finished, not right now. The callback only gets its turn once all the plain code has finished.

⚡ Keep the id so you can stop it

Write:

const id = setInterval(() => {
  seconds++
  if (seconds === 3) {
    clearInterval(id)
  }
}, 1000)

Meaning: setInterval runs the callback again and again, every 1000 milliseconds in this example. setInterval returns an id, the timer's number. clearInterval(id) stops that repeating timer, so you must keep the id. seconds is a counter variable that starts at 0, so this timer stops on its third run. A setTimeout timer can also be cancelled before it runs, with clearTimeout(id).

What you will learn