Scheduling and cancelling a timeout

suggest change

setTimeout() schedules a callback after at least the requested delay in milliseconds. It does not pause execution, and the callback may run later if the event loop is busy or the runtime applies timer throttling.

const timeoutId = setTimeout(() => {
  console.log("hello");
}, 1000);

Loop variables

A loop declared with var has one function-scoped binding, so every callback observes its final value:

// eslint-disable-next-line no-var -- Demonstrates var's function scope.
for (var i = 0; i < 3; i += 1) {
  setTimeout(() => console.log(i), 0);
}
// Logs 3 three times.

Declare the counter with let to create a new binding for each iteration:

for (let i = 0; i < 3; i += 1) {
  setTimeout(() => console.log(i), 0);
}
// Logs 0, 1, 2.

Order of execution

Even a delay of 0 schedules work for a later task. The current call stack and queued microtasks run before the timer callback:

setTimeout(() => console.log("timer"), 0);
Promise.resolve().then(() => console.log("microtask"));
console.log("synchronous");

// synchronous
// microtask
// timer

Do not use a zero-delay timeout as a precise timing mechanism. Its purpose is to schedule a future task.

Cancelling a timeout

Pass the returned identifier to clearTimeout() before the callback runs:

const timeoutId = setTimeout(() => {
  console.log("This will not run");
}, 1000);

clearTimeout(timeoutId);

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents