Timers – setTimeout, setInterval, clearTimeout, and clearInterval
Timers schedule a function to run later. setTimeout runs a function once after a delay, and setInterval runs it repeatedly with the delay between runs. Each returns an ID, which clearTimeout or clearInterval uses to cancel the timer. The delay is given in milliseconds, so 1000 is one second.
const id = setTimeout(callback, delay, arg1, arg2);clearTimeout(id);
const id2 = setInterval(callback, delay, arg1, arg2);clearInterval(id2);The timer functions belong to the browser and to Node rather than to the JavaScript language, but both provide them under the same names.
Running code once after a delay
Section titled “Running code once after a delay”setTimeout does not pause the program. It schedules the callback and returns at once, so the code after it carries on running:
console.log('Kettle on');
setTimeout(() => { console.log('Tea is ready');}, 1000);
console.log('Waiting...');This prints:
Kettle onWaiting...Tea is readyThe last line appears about a second after the first two.
Passing arguments to the callback
Section titled “Passing arguments to the callback”Arguments after the delay are passed to the callback when it runs. This lets you pass a named function without wrapping it in another function:
function remind(task, person) { console.log(`${person}, remember to ${task}`);}
setTimeout(remind, 500, 'water the plants', 'Sam');This prints:
Sam, remember to water the plantsPass the function itself, as in setTimeout(remind, 500). Writing setTimeout(remind(), 500) calls remind straight away and passes its return value to setTimeout instead.
Cancelling a timeout
Section titled “Cancelling a timeout”Keep the ID that setTimeout returns, and pass it to clearTimeout to stop the callback running:
const reminder = setTimeout(() => { console.log('This never prints');}, 1000);
clearTimeout(reminder);console.log('Reminder cancelled');This prints:
Reminder cancelledBrowsers return a number as the ID, and Node returns a Timeout object. Treat it as an opaque value and only pass it back to the clearing function. Clearing a timer that has already run, or passing undefined, does nothing and raises no error.
Repeating with setInterval
Section titled “Repeating with setInterval”setInterval keeps calling its callback until clearInterval stops it. A countdown can clear its own interval when it reaches zero:
let remaining = 3;
const countdown = setInterval(() => { console.log(remaining); remaining -= 1; if (remaining === 0) { clearInterval(countdown); console.log('Lift-off'); }}, 1000);This prints:
321Lift-offAn interval that is never cleared runs for as long as the page is open, and in Node it keeps the program from exiting.
When each run must wait for the previous one to finish, such as a network request that can be slow, chain setTimeout calls instead. Each run schedules the next, so runs cannot overlap:
let ticks = 0;
function tick() { ticks += 1; console.log(`tick ${ticks}`); if (ticks < 3) { setTimeout(tick, 500); }}
setTimeout(tick, 500);This prints:
tick 1tick 2tick 3The delay is a minimum
Section titled “The delay is a minimum”A timer’s callback runs no sooner than the delay, but it can run later. The callback waits until the code that is currently running has finished, and until any promise callbacks already queued have run. That is why a delay of 0 still runs after the rest of the script:
setTimeout(() => console.log('timeout'), 0);Promise.resolve().then(() => console.log('promise'));console.log('script');This prints:
scriptpromisetimeoutEvent Loops explains this order. Browsers also add delays of their own: once timers have been nested five levels deep, the shortest delay becomes 4 milliseconds, and tabs in the background are usually limited to one run per second or less. A delay larger than 2,147,483,647 milliseconds, which is about 24.8 days, overflows and runs the callback almost at once. Timers therefore suit reminders and polling, but not accurate timekeeping, so a clock should read the current time on each run rather than count the runs.
Steve Griffith covers this topic in his video JavaScript Timers - setTimeout, setInterval, clearTimeout, and clearInterval.