JavaScript setInterval()

Introduction

JavaScript is widely used to create dynamic and interactive web applications. Many real-world features—like clocks, auto-refreshing data, animations, and notifications—require code to run repeatedly at fixed intervals.

This is where setInterval() comes into play.

The setInterval() function allows you to execute a piece of code repeatedly after a specified time interval. It is a powerful tool for scheduling recurring tasks in JavaScript applications.

In this article, we will explore what setInterval() is, how it works, and how to use it effectively with real-world examples and best practices.

What is JavaScript setInterval()?

setInterval() is a built-in JavaScript function that repeatedly executes a function or code block after a fixed delay (in milliseconds).

 In simple terms:

setInterval() = Run code repeatedly after a fixed time interval

📖
Important:
  • Executes code repeatedly after a delay.
  • Works with event loop.
  • Can be stopped using clearInterval.
  • May be inaccurate due to blocking code.
  • Use carefully to avoid performance issues.

Basic Example


setInterval(function () {
 console.log("Hello every 2 seconds");
}, 2000);

Output:

The message prints every 2 seconds continuously.

Why setInterval() is Used

setInterval() is commonly used in modern applications for:

1. Repeated Tasks

Run code at regular intervals.

2. Real-Time Updates

Auto-refresh data (e.g., dashboards, stock prices).

3. Animations

Create simple animations or transitions.

4. Timers and Clocks

Display time or countdowns.

5. Polling APIs

Fetch data periodically from servers.

Syntax


setInterval(function, delay, param1, param2, ...);

Parameters:

  1. function → Function to execute repeatedly
  2. delay → Time in milliseconds
  3. parameters (optional) → Values passed to the function

Example with Parameters


function greet(name) {
 console.log("Hello " + name);
}

setInterval(greet, 2000, "John");

How setInterval() Works

setInterval() works with the JavaScript event loop, just like setTimeout().

Step-by-step:

  1. Function is registered with setInterval()
  2. Timer runs in Web APIs
  3. After every delay, callback is added to Callback Queue
  4. Event Loop pushes it to Call Stack when free
  5. Function executes repeatedly

Note: Execution may be delayed if the call stack is busy.

Example:

I will show you many examples.

Example 1: Simple Interval


setInterval(() => {
 console.log("Running...");
}, 1000);

Example 2: Stop setInterval

In the example below, you will see that we stop after 5 seconds.


let timer = setInterval(() => {
 console.log("Hello");
}, 1000);

setTimeout(() => {
 clearInterval(timer);
}, 5000);

Example 3: Digital Clock

You can create a Digital Clock using the code below.


setInterval(() => {
 let now = new Date();
 console.log(now.toLocaleTimeString());
}, 1000);

Example 4: Counter


let count = 0;

let timer = setInterval(() => {
 count++;
 console.log(count);

 if (count === 5) {
   clearInterval(timer);
 }
}, 1000);

Real-Life Example: Auto Refresh Data

Suppose you have to refresh data at a particular time for the stock market.


function fetchData() {
 console.log("Fetching latest data...");
}

setInterval(fetchData, 3000);

Common Mistakes

There are many common mistakes.

1. Not Clearing Interval

If we don’t use clearInterval() after using setInterval(), then we will get a memory issue.


setInterval(() => {
 console.log("Runs forever");
}, 1000);

2. Overlapping Execution

 If heavyTask takes longer than 1 second, calls may overlap.


setInterval(() => {
 heavyTask();
}, 1000);

3. Incorrect Delay Assumptions

In the example below, it does not run instantly.


setInterval(() => {}, 0);

Interview Questions

Q 1: What is setInterval()?
Ans: A function that executes code repeatedly at fixed intervals.
Q 2: Difference between setTimeout and setInterval?
Ans: setTimeout → runs once
setInterval → runs repeatedly
Q 3: How to stop setInterval?
Ans: clearInterval(timerId);
Q 4: Can setInterval be inaccurate?
Ans: Yes, due to event loop and blocking code.
Q 5: What happens if delay is 0?
Ans: Still goes through event loop; not immediate.

Conclusion

JavaScript setInterval() is a powerful tool for executing code repeatedly at fixed intervals. It is widely used in real-world applications like timers, animations, and live data updates.