setTimeout
Run code later.
Set timeout asks JavaScript to run a function later, after a delay in milliseconds. It's the easiest way to see asynchronous code in action, because the order of the output might surprise you.

- Run a function later
- Delay in milliseconds
- The order surprises
Out of order
We log one. Then set timeout schedules a function for half a second later. Then we log three. JavaScript doesn't wait, so three appears before two. Even a delay of zero runs after the normal code finishes. Run it.
console.log("1. Start");
setTimeout(() => {
console.log("2. Half a second later");
}, 500);
setTimeout(() => console.log("2b. Zero delay, still later"), 0);
console.log("3. End of the script");1. Start 3. End of the script 2b. Zero delay, still later 2. Half a second later
setInterval and clearInterval
Set interval repeats a function every so often. It returns an i d, and clear interval with that i d stops it. Here we count down from three, once every two hundred milliseconds, then stop. Run it.
let count = 3;
const id = setInterval(() => {
console.log("Tick", count);
count--;
if (count === 0) {
clearInterval(id);
console.log("Lift off!");
}
}, 200);Tick 3 Tick 2 Tick 1 Lift off!
Summary
Set timeout runs code once after a delay, and set interval repeats it until you clear it. Async code runs after the normal code. Next, why callbacks get messy.
Key takeaways- setTimeout(fn, ms)
- setInterval / clearInterval
- Runs after normal code