Lesson 36 / 38

setTimeout & setInterval

Scheduling code to run later or repeatedly.

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.