JavaScript
setInterval
asynchronous programming
web development
coding techniques

Can you use setInterval to call functions asynchronously?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

setInterval can schedule a function repeatedly, but it does not make blocking work asynchronous by itself. It simply places callbacks onto the JavaScript event loop at roughly regular intervals, which means async functions work with it, but overlapping execution and timing drift still need explicit handling.

What setInterval Actually Guarantees

When you call setInterval(fn, delay), the runtime attempts to queue fn every delay milliseconds. If the event loop is busy, the callback runs later.

javascript
1let ticks = 0;
2const id = setInterval(() => {
3  ticks += 1;
4  console.log('tick', ticks, Date.now());
5  if (ticks === 3) {
6    clearInterval(id);
7  }
8}, 1000);

This is asynchronous scheduling in the event-loop sense, but it is not real-time and it does not promise non-overlap.

You Can Use async Functions, but They May Overlap

Passing an async function is allowed, but setInterval does not wait for one run to finish before queuing the next.

javascript
1const id = setInterval(async () => {
2  await new Promise(resolve => setTimeout(resolve, 1500));
3  console.log('work done');
4}, 1000);
5
6setTimeout(() => clearInterval(id), 5000);

Here, the work takes longer than the interval, so multiple executions can be in flight at once.

That is often the real answer to the question: yes, you can use it with async functions, but you must decide whether overlap is acceptable.

Prevent Overlap with a Guard

If only one run should happen at a time, use a guard flag.

javascript
1let running = false;
2
3const id = setInterval(async () => {
4  if (running) return;
5  running = true;
6
7  try {
8    await doAsyncWork();
9  } catch (err) {
10    console.error(err);
11  } finally {
12    running = false;
13  }
14}, 1000);

This pattern is simple and often good enough for polling or periodic refresh tasks.

Recursive setTimeout Is Often Safer

For many async polling loops, recursive setTimeout is easier to reason about because the next run is scheduled only after the current run finishes.

javascript
1let stopped = false;
2
3async function poll() {
4  if (stopped) return;
5
6  try {
7    await doAsyncWork();
8  } catch (err) {
9    console.error('poll error', err);
10  } finally {
11    setTimeout(poll, 1000);
12  }
13}
14
15poll();

This avoids uncontrolled overlap and makes backoff strategies easier to implement.

Error Handling and Cleanup

Async interval code still needs proper cleanup. In browser components and UI frameworks, forgetting to clear intervals can leave stale polling logic running after navigation or unmount.

If the work performs fetch calls, pair interval cleanup with request cancellation where appropriate.

javascript
1const controller = new AbortController();
2
3async function doAsyncWork() {
4  const response = await fetch('/api/status', { signal: controller.signal });
5  return response.json();
6}
7
8// later
9controller.abort();
10clearInterval(id);

That prevents both repeated scheduling and long-lived in-flight work from continuing after shutdown.

Clearing the interval also does not cancel async work that has already started. If in-flight operations matter, pair timer cleanup with explicit cancellation or stale-result guards.

Common Pitfalls

Assuming setInterval serializes async work is the main mistake. It does not wait for earlier runs to finish.

Ignoring timer cleanup in UI code causes duplicate polling and memory leaks.

Using fixed intervals during failures without backoff can create unnecessary load when a remote service is already unhealthy.

Summary

  • 'setInterval can schedule async functions, but it does not prevent overlap.'
  • The callbacks are asynchronous only in the event-loop scheduling sense.
  • Use a guard flag or recursive setTimeout when overlapping work is undesirable.
  • Always pair repeating async work with explicit error handling and cleanup.

Course illustration
Course illustration

All Rights Reserved.