SkillByAIOpen interactive version →

Lesson 37 / 40

setTimeout & setInterval

Schedule code with setTimeout and setInterval, clear timers and know why delays are only minimums.

setTimeout

Runs a callback once, after at least the given delay in milliseconds.

const id = setTimeout(() => console.log("Runs once, later"), 2000);
clearTimeout(id);  // cancels it before it fires

setInterval

Repeats a callback on a fixed interval until explicitly cleared.

const id = setInterval(() => console.log("Tick"), 1000);
setTimeout(() => clearInterval(id), 5000);

Not guaranteed exact

The delay is a minimum, not a guarantee — a busy call stack can delay a timer's callback.