setTimeout/setInterval
Timers run code after a delay or repeatedly at an interval.
In this page:
Syntax
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
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
- Forgetting to clear intervals
- Assuming exact timing
- 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: