Skip to content

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.

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 on
Waiting...
Tea is ready

The last line appears about a second after the first two.

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 plants

Pass the function itself, as in setTimeout(remind, 500). Writing setTimeout(remind(), 500) calls remind straight away and passes its return value to setTimeout instead.

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 cancelled

Browsers 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.

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:

3
2
1
Lift-off

An 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 1
tick 2
tick 3

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:

script
promise
timeout

Event 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.