AI Hints
Home›JavaScript Tutorial›Asynchronous Basics
JavaScript · Lesson 80 of 138

setTimeout

Run code later.

⏱ 2 min read▶ Video at 1:36:55🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

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.

setTimeout
From the video: setTimeout
  • 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.

app.jsjavascript
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");
Output
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.

app.jsjavascript
let count = 3;

const id = setInterval(() => {
  console.log("Tick", count);
  count--;
  if (count === 0) {
    clearInterval(id);
    console.log("Lift off!");
  }
}, 200);
Output
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
Next up: Callback Hell — nesting problems