JavaScript Reference ยท Promises and Async
The setInterval() function
Reference for JavaScript setInterval(): running code repeatedly, stopping with clearInterval(), drift and overlap pitfalls, and the recursive setTimeout option.
setInterval() calls a function again and again, with a fixed delay between the start of each call, until you cancel it. It returns a timer id, which you pass to clearInterval() to stop it.
Use it for simple, regular jobs such as updating a clock or polling a status. For work that must not overlap itself, or whose duration varies, a chain of setTimeout() calls is usually a better fit.
const id = setInterval(() => console.log("tick"), 1000); // later clearInterval(id);
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
setInterval(callback) setInterval(callback, delay) setInterval(callback, delay, arg1, arg2, /* โฆ, */ argN)
| Name | Description |
|---|---|
callback |
The function to call on each tick. |
delay |
Milliseconds between calls. Optional; defaults to 0, which is rarely what you want. |
arg1 โฆ argN |
Extra arguments passed to callback on every call. |
Return value: a timer id for clearInterval(): a positive integer in browsers, a Timeout object in Node.js.
Usage notes
- Nothing happens at time zero. The first call occurs after one full delay.
- Intervals can drift and bunch up. If the thread is busy, ticks are delayed, and the browser does not queue an unlimited backlog. Do not count ticks to measure time; compare timestamps.
- No overlap protection for async work. If the callback starts a request that takes longer than the delay, a second request begins before the first ends. For polling, schedule the next
setTimeout()when the previous work finishes. - Always keep the id so you can stop it. An interval that is never cleared keeps running (and, in Node.js, keeps the process alive).
- Clean up in components. Clear the interval when a page section is removed, or the callback keeps running against stale elements.
- Throttling. Hidden tabs slow timers down, often to once a second or less.
- Animation: use
requestAnimationFrame()instead of a 16 ms interval; it syncs with the display and pauses in hidden tabs. - Same pitfalls as
setTimeout(): pass a function reference (not a call), avoid string callbacks, and watchthisin method callbacks.
Browser support
setInterval() is supported in every browser, Web Worker and Node.js.