← Back to Node.js Course | Chapter 4: Async Programming | Lesson 6 of 7

setTimeout/setInterval

Timers run code after a delay or repeatedly at an interval.

In this page:

  1. setTimeout/setInterval
Syntax
javascript
const timeoutId = setTimeout(callback, milliseconds);
const intervalId = setInterval(callback, milliseconds);
clearTimeout(timeoutId);
clearInterval(intervalId);

setTimeout/setInterval

setTimeout runs a callback once after at least the given milliseconds and setInterval repeats it. Both return handles that you pass to clearTimeout or clearInterval. Timer delays are minimums, not guarantees, because the event loop must be free.

Note: Call unref() on a timer to let the process exit even if the timer is pending.

Example: setTimeout/setInterval

javascript
let count = 0;
const id = setInterval(() => {
  count += 1;
  console.log("tick", count);
  if (count === 3) {
    clearInterval(id);
    console.log("stopped");
  }
}, 5);
const t = setTimeout(() => console.log("never runs"), 1000);
clearTimeout(t);

// Output:
// tick 1
// tick 2
// tick 3
// stopped

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Forgetting to clear intervals
  2. Assuming exact timing
  3. Using a string instead of a function
Chapter Summary
  • setTimeout runs once
  • setInterval repeats
  • clearTimeout and clearInterval cancel
  • Delays are minimums
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.