Recursive Timer with JavaScript setTimeout()

A recursive timer schedules the next setTimeout() from inside the current callback. Unlike setInterval(), this makes it easier to wait until one run finishes before scheduling the next.

function repeat() {
  console.log("run");
  setTimeout(repeat, 1000);
}
repeat();

Why Use Recursive setTimeout() Instead of setInterval()? Top ↑

With setInterval(), the next callback is scheduled according to the interval even if previous work is slow. A recursive timeout schedules only after your callback reaches the scheduling line, so you can control when the next run begins.

Basic Recursive Timer Example Top ↑

let timerId;
function tick() {
  document.getElementById("output").textContent = new Date().toLocaleTimeString();
  timerId = setTimeout(tick, 1000);
}
tick();

See the existing recursive timer demo.

Stop a Recursive Timer Top ↑

clearTimeout(timerId);

Store the most recently returned timeout ID. See clearTimeout and resetting timers.

Recursive Timer for Asynchronous Work Top ↑

async function poll() {
  try {
    await refreshData();
  } finally {
    timerId = setTimeout(poll, 5000);
  }
}
poll();

This avoids starting the next refresh while the previous refresh is still running.

Change the Delay Between Runs Top ↑

let delay = 1000;
function repeat() {
  console.log(delay);
  delay = Math.min(delay * 2, 8000);
  timerId = setTimeout(repeat, delay);
}

This pattern can implement a simple backoff strategy.

Recursive Timers Are Still Not Exact Clocks Top ↑

setTimeout() specifies a minimum delay. Browser scheduling, background-tab throttling, and long tasks can make the actual delay longer. If a display must reflect real elapsed time, calculate from timestamps rather than incrementing a counter and assuming each callback arrived on time.

Common Recursive Timer Mistakes Top ↑

  • Calling the function immediately inside setTimeout(repeat(), 1000) instead of passing the function.
  • Forgetting to store the new timeout ID.
  • Creating multiple recursive chains by starting the function more than once.
  • Assuming the delay is exact.
  • Not stopping the chain when the UI no longer needs it.

Related: real-time clock.

setTimeout() Stopwatch




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer