🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEjavascript

javascript Documentation

LOADING ENGINE...

setInterval()

AI & DATA SCIENCE // set-interval

setInterval calls a function repeatedly at a specified interval. Returns an ID — always store it to cancel with clearInterval().

Syntax

const id = setInterval(callback, interval);
clearInterval(id); // stop it

Deep Dive Course

**setInterval** repeatedly fires a callback every `interval` milliseconds until **clearInterval** is called. Like setTimeout, the interval is a minimum. If the callback takes longer than the interval, calls can stack up. Prefer `setTimeout` recursion for dynamic intervals or long-running callbacks.

1Understanding setInterval()

setInterval repeatedly fires a callback every interval milliseconds until clearInterval is called. Like setTimeout, the interval is a minimum. If the callback takes longer than the interval, calls can stack up. Prefer setTimeout recursion for dynamic intervals or long-running callbacks.

💡

For reliable intervals with long callbacks, use recursive setTimeout: after the callback runs, schedule the next one. This prevents piling up.

editor.html
// Countdown timer
let count = 10;
const timer = setInterval(() => {
  console.log('T-' + count);
  count--;
  if (count < 0) {
    clearInterval(timer);
    console.log('Liftoff! 🚀');
  }
}, 1000);
localhost:3000

2Practical Example

Here is a real-world application of setInterval() showing how it is used in production JavaScript code.

editor.html
// Reliable interval with recursive setTimeout
function reliableInterval(fn, delay) {
  let id;
  function tick() {
    fn();
    id = setTimeout(tick, delay); // schedule next AFTER completion
  }
  id = setTimeout(tick, delay);
  return () => clearTimeout(id); // return cancel function
}

const stop = reliableInterval(() => console.log('ping'), 1000);
localhost:3000

3Best Practices

Follow these guidelines when working with setInterval():

1. Always store the ID and call clearInterval when done

2. Use clearInterval in cleanup (useEffect return, component unmount)

3. For long-running callbacks, use recursive setTimeout instead

⚠️

Tip: For reliable intervals with long callbacks, use recursive setTimeout: after the callback runs, schedule the next one. This prevents piling up.

editor.html
// Countdown timer
let count = 10;
const timer = setInterval(() => {
  console.log('T-' + count);
  count--;
  if (count < 0) {
    clearInterval(timer);
    console.log('Liftoff! 🚀');
  }
}, 1000);
localhost:3000

Examples

Example 01Basic Usage
// Countdown timer
let count = 10;
const timer = setInterval(() => {
  console.log('T-' + count);
  count--;
  if (count < 0) {
    clearInterval(timer);
    console.log('Liftoff! 🚀');
  }
}, 1000);
Example 02Advanced Example
// Reliable interval with recursive setTimeout
function reliableInterval(fn, delay) {
  let id;
  function tick() {
    fn();
    id = setTimeout(tick, delay); // schedule next AFTER completion
  }
  id = setTimeout(tick, delay);
  return () => clearTimeout(id); // return cancel function
}

const stop = reliableInterval(() => console.log('ping'), 1000);

Best Practices

  • Always store the ID and call clearInterval when done
  • Use clearInterval in cleanup (useEffect return, component unmount)
  • For long-running callbacks, use recursive setTimeout instead

Interview Question

What is the problem with setInterval for long-running callbacks?

Hint: Callbacks pile up.

If a setInterval callback takes longer than the interval, the next call is queued before the previous finishes. This can cause 'callback pileup' — multiple instances running simultaneously, creating race conditions and memory issues. Recursive setTimeout avoids this: the next call is only scheduled AFTER the current one completes.

Exercises

MediumPractice using setInterval() in a real scenario.
View Solution
// Countdown timer
let count = 10;
const timer = setInterval(() => {
  console.log('T-' + count);
  count--;
  if (count < 0) {
    clearInterval(timer);
    console.log('Liftoff! 🚀');
  }
}, 1000);

Frequently Asked Questions

What is the problem with setInterval for long-running callbacks?

If a setInterval callback takes longer than the interval, the next call is queued before the previous finishes. This can cause 'callback pileup' — multiple instances running simultaneously, creating race conditions and memory issues. Recursive setTimeout avoids this: the next call is only scheduled AFTER the current one completes.

Related Functions

setTimeoutEvent LoopPromises