Call a function every second in JavaScript (setInterval, cleanup)

JavaScript call function every second and every 5 seconds with setInterval and clearInterval, recursive setTimeout when work overlaps, setTimeout delays, async delay helper, timer cleanup, and Node/browser throttling caveats. Snippets include short expected-output notes after editorial runs in Node.

Published

Updated

Read time 4 min read

Reviewed byDeepak Prasad

Call a function every second in JavaScript (setInterval, cleanup)

Timers let you build clocks, polling, and animations. For javascript call function every second, js repeat function every second, or javascript run function every 5 seconds, the usual tool is setInterval. The delay is always in milliseconds: 1000 for one second, 5000 for five. This page also covers recursive setTimeout when a tick might outlast its interval, clearInterval, and a small async / Promise delay pattern. For background on timers in the browser, see JavaScript timed events.

Tested on: Node.js v20.18.2. A short note after each snippet describes what you should see in the console.


Quick reference

Pick setInterval for fixed cadence when each tick finishes quickly; pick recursive setTimeout when a tick might still be running when the next deadline hits; use setTimeout alone for one-shot delays.

Goal API
Fixed cadence, fast callbacks setInterval + clearInterval
Cadence waits for slow callbacks Recursive setTimeout
Single delayed run setTimeout + clearTimeout
await pause await new Promise((r) => setTimeout(r, ms))

1. setInterval — javascript repeat every second

This section shows the handle returned by setInterval, how to stop after N ticks, and how extra arguments are forwarded into the callback.

setInterval(callback, delay, ...args) schedules callback every delay ms. It returns a handle you must pass to clearInterval when you are done.

1a. Stop after three real one-second ticks

javascript
let count = 0;
const id = setInterval(() => {
  count += 1;
  console.log("tick", count);
  if (count === 3) {
    clearInterval(id);
  }
}, 1000);
Output

You should see 3 lines: tick 1, then tick 2, then tick 3.

1b. Extra arguments after the delay

Arguments after delay are forwarded to callback (same signature on MDN).

javascript
let i = 0;
const id = setInterval(
  (label) => {
    i += 1;
    console.log(`${label}: ${i}`);
    if (i === 2) {
      clearInterval(id);
    }
  },
  1000,
  "Date",
);
Output

You should see 2 lines: Date: 1, then Date: 2.


2. setTimeout — run once, or chain for javascript loop every second

One-shot timers are the building block for delays, debouncing, and “schedule next when done” loops.

setTimeout runs callback once after delay ms. The event loop may defer firing slightly under load.

javascript
setTimeout((msg) => console.log(msg), 100, "after 100ms");
Output

You should see one line like: after 100ms.

In production you might use 3000 for three seconds; the pattern is identical—only the delay literal changes.


3. Recursive setTimeout when work can overlap (MDN pattern)

When callback duration is unpredictable, wall-clock setInterval can enqueue overlapping work; scheduling the next timeout after the body finishes preserves back-pressure.

javascript
let i = 0;
function loop() {
  i += 1;
  console.log("recursive", i);
  if (i < 3) {
    setTimeout(loop, 100);
  }
}
setTimeout(loop, 100);
Output

You should see 3 lines: recursive 1, then recursive 2, then recursive 3.

Use 1000 instead of 100 in both places for js run function every second.


4. async / await delay (not a timer loop by itself)

Promise-wrapping setTimeout fits sequential async steps; add a loop and a cancellation flag (or AbortController) if you need a polled rhythm alongside await I/O. See also promises and await.

javascript
(async () => {
  function delay(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
  }
  console.log("Starting the delayed function...");
  await delay(50);
  console.log("50 ms have passed, continuing the function...");
})();
Output

You should see 2 lines: Starting the delayed function..., then 50 ms have passed, continuing the function....

Combine with a while loop if you need javascript repeat function every second and await network I/O between ticks—still cancel with a boolean flag or AbortController, not shown here.


5. call function every 5 seconds javascript

The API is identical to one-second polling—only the millisecond literal changes (5000 instead of 1000). For example: setInterval(fn, 5000) or a chained setTimeout(fn, 5000).


6. Cleanup and precision

Timers keep the runtime busy until cleared—treat handles like any other disposable resource.

  • Always clearInterval(id) (or clearTimeout) when a component unmounts, a user logs out, or a job ends—otherwise timers keep the event loop alive in Node and waste work in the browser.
  • Background tabs may throttle timers; do not rely on wall-clock accuracy for security or billing.
  • For heavy periodic work, consider Web Workers or moving logic server-side.

Summary

Use setInterval for simple periodic callbacks, setTimeout chains when ticks must not overlap, and Promise delays inside async flows—always clear handles on teardown.

  • setInterval(fn, ms) repeats until clearInterval; pass extra args after the delay to forward into fn.
  • Recursive setTimeout avoids overlapping ticks when each iteration can exceed the interval.
  • setTimeout runs once; chain or combine with async/await for sequential delays.
  • Always clear handles on teardown; treat intervals as minimum spacing, not hard real-time.

References

MDN and Node documentation for timers used in javascript repeat function every second patterns.


Frequently Asked Questions

1. How do I javascript call function every second on repeat?

Use setInterval(callback, 1000). One second is 1000 milliseconds. Store the returned handle and pass it to clearInterval when you want to stop.

2. How is javascript call function every 5 seconds different?

Only the delay argument changes: setInterval(callback, 5000) for a five-second cadence.

3. setInterval or recursive setTimeout for javascript repeat function every second?

If each tick might take longer than the interval—for example slow network polling—prefer scheduling the next setTimeout at the end of the work so ticks do not overlap. setInterval fires on a wall clock regardless of whether the previous callback finished.

4. Does the first setInterval callback run immediately?

No. The first run happens after the first delay elapses. For an immediate run plus interval, invoke the function once, then start setInterval.

5. Are timers exact in the browser?

No. Background tabs throttle timers, and the event loop can delay callbacks. Treat intervals as minimum spacing, not hard real-time guarantees.

6. Does clearTimeout work on a setInterval id?

In browsers, timer ids share a pool; MDN notes clearTimeout and clearInterval are often interchangeable in practice, but matching clearInterval to setInterval keeps code clear.
Olorunfemi Akinlua

Boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs …