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...')
setTimeout(function, delay)takes two things: the function to run later, and the delay in milliseconds.() => { ... }is the function to run later. A function you pass to other code to be called later is called a callback. The callback's body does not run yet. It is only scheduled.2000means 2 seconds. Do not write2: that is only 2 milliseconds.const id = ...keeps the timer's id, a number thatsetTimeoutreturns. You use this number to cancel the timer.
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)
setInterval(function, delay)runs the callback everydelaymilliseconds, again and again.setIntervalreturns an id too. Keep that id inconst id.clearInterval(id)stops the interval (the repeating timer) with that id. Without the id, there is no way to stop it.
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))
return new Promise(...)makes this function return a Promise right away, not the value itself.resolveis the Promise's "done" button. The value you pass toresolve(...)becomes the Promise's result.resolve(value)is called inside thesetTimeoutcallback. So the Promise only finishes oncemsmilliseconds have passed.
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
- A
setInterval(...)withoutconst id =can't be stopped. It keeps running even when it is no longer needed. setTimeout(greet(), 1000)runsgreetright now, because of the brackets aftergreet. WritesetTimeout(greet, 1000)orsetTimeout(() => greet(), 1000).- If
resolveis called outside thesetTimeoutcallback, the Promise finishes right away, without waiting for the delay. - The delay is the shortest wait, not an exact time. If the browser is busy, the callback can run a little late.
- In a tab hidden behind another tab, the browser makes timers slower. Firefox runs them at most once per second, and Chrome may run them only once per minute after the tab has been hidden for more than 5 minutes. A countdown that subtracts 1 on each pass then goes wrong, because it runs less often.
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).