Table of contents
1.
Introduction
1.1.
What is Scheduling a Call in Javascript?
2.
What is Javascript SetInterval()?
3.
Syntax of SetInterval() in Javascript
4.
Parameters of SetInterval() in Javascript
5.
Examples of Javascript setInterval()
5.1.
Example 1: Display a Message
5.2.
Example 2: Display a dialogue box
5.3.
Example 3: Digital Clock
6.
Alternative to Javascript SetInterval()
7.
What is Garbage Collection?
8.
Application of setInterval() in Javascript
9.
Frequently Asked Questions
9.1.
What does the javascript setInterval() method do?
9.2.
Can we pause setInterval in JavaScript?
9.3.
How do you cancel a setTimeout or setInterval in JavaScript?
9.4.
What is setTimeout and setInterval in JavaScript?
10.
Conclusion
Last Updated: Jan 7, 2025
Easy

setInterval() in JavaScript

Author Nidhi Kumari
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In JavaScript, the setInterval() function is a built-in method used to repeatedly execute a specified function or code block at fixed time intervals. It continues to run until explicitly stopped using clearInterval(). This feature is useful for creating timers, animations, and periodic tasks in web applications, making it essential for dynamic behavior on web pages.

setInterval( ) in JavaScript

Running a program later or periodically is possible using JS. This is called "scheduling a call" or  "scheduling a function call". This article will cover the Javascript setintervel() method for scheduling a call. Before moving on to the method, let’s briefly discuss scheduling a call.

What is Scheduling a Call in Javascript?

There are several cases in which a coder might choose to delay the execution of a function rather than call it immediately. This type of action is referred to as scheduling a call in JS.

JS framework provides two ways to schedule a call.

  1. Using the javascript setTimeout() method enables us to execute a method once after the interval.
     
  2. Using the javascript setInterval() method, With the help of setInterval, we can run a function repeatedly, beginning after the interval and repeating continuously at the given time.
     

Here we will only discuss the javascript setIntervel() method. To learn more, you can visit our article on Scheduling.

What is Javascript SetInterval()?

One can periodically execute a function using the javascript setInterval() method. After a fixed interval of time, the function begins to execute, and at that point, it repeats the function call continuously.

Syntax of SetInterval() in Javascript

The syntax of the javascript setInterval() method is as follows:

const timerId = setInterval(function, [interval], [arg1], [arg2], ...)
You can also try this code with Online Javascript Compiler
Run Code

Parameters of SetInterval() in Javascript

The parameters used in the syntax are as follows:

  • Function: The function is a block of code.
     
  • Interval Time: The interval is the time interval between the execution of the code. The interval time will be in milliseconds.
     
  • Arg: Arg1 and arg2 are the arguments provided by the users. 
     

A positive integer, known as interval_ID, results from the setInterval() function.

Note: If you want to execute your function only once after a fixed time, you can use the setTimeout() method.

Examples of Javascript setInterval()

To understand the javascript setInterval() method, see the examples below. 

Example 1: Display a Message

Here, we are creating a function that displays “Hello Ninja” in the browser console at intervals of 2000 milliseconds(2 seconds).

<!DOCTYPE html>
<html>
   <body>
      <h2>The setInterval() Method</h2>
      <p id="CN"></p>
      <script>
         const element = document.getElementById("CN");
         setInterval(function() {element.innerHTML += "Hello Ninja"}, 2000);
      </script>
   </body>
</html>
You can also try this code with Online Javascript Compiler
Run Code

 

Output:

function that displays “Hello Ninja” in the browser console

Example 2: Display a dialogue box

Here is the code to display a dialogue box every four seconds.

<!DOCTYPE html>
<html>
   <head>
      <title> setInterval() method </title>
   </head>
   <body>
      <h1> Code Studio</h1>
      <h3> The setInterval() method </h3>
      <p> The time interval for the dialogue box is four seconds. </p>
      <script>  
         let msg = setInterval(CodingNinjas, 4000);  
           
         function CodingNinjas() {  
         alert(" Welcome to the Coding Ninjas Studio Library. ");  
         }
      </script>  
   </body>
</html>
You can also try this code with Online Javascript Compiler
Run Code

 

Output:

dialogue box every four seconds.


You can practice by yourself with the help of Online Javascript Compiler for better understanding.

Example 3: Digital Clock

Here is an example of a digital clock using the javascript setInterval method.

<!DOCTYPE html>
<html>
   <head>
      <title> A digital clock</title>
   </head>
   <body>
      <h3> Example of the setInterval() method. </h3>
      <h4>Display the Current Time:</h4>
      <span id = "CN" style = "background-color: #AA98A9; padding: 15px; border: 2px solid blue;" >
      </span>
      <script>
         const root = document.getElementById('CN')
         
         // setInterval function
         setInterval(() => {
            const date = new Date();
            root.innerHTML = date.toLocaleTimeString();
         
         }, 1000);
      </script>
   </body>
</html>
You can also try this code with Online Javascript Compiler
Run Code

 

Output:

digital clock using the javascript setInterval method.

Alternative to Javascript SetInterval()

The nested setTimeout() method in JS can be used as the alternative to javascript SetInterval() method.

One can use the following format to use the nested setTimeout() method.

let interval = 1000;    //first time
let function = setTimeout(function request() {
  if (request failed) {
    interval += 1000;    //second request
  }
  function = setTimeout(request, interval);

}, interval);
You can also try this code with Online Javascript Compiler
Run Code


Output

Request failed. Retrying in 2 seconds.
Request failed. Retrying in 3 seconds.
Request failed. Retrying in 4 seconds.
...


The nested setTimeout() method is more flexible than the javascript setInterval() method. As you can see, in the second request, the delay depends on the response to the first request. 

What is Garbage Collection?

When you pass a function to the javascript setInterval() function, an internal reference is created. The scheduler of the system stores this generated reference. 

Despite the fact that there are no other references to the function, it stops it from being garbage collected.

Until the javascript clearInterval() method is invoked, the setInterval() function remains in memory.

// until the scheduler executes the function, it remains in the memory.
setTimeout(function()/code {arguments}, 100);
You can also try this code with Online Javascript Compiler
Run Code

 

Even if the scheduled task is very small, it is preferable to cancel it when we no more require it. When a function refers to the external function, external variables also exist. They could use a lot more memory than the actual function.

Application of setInterval() in Javascript

There are many applications that make use of JavaScript's setInterval() function, including:

  • Animations: It can be made by repeatedly changing an element's position, size, or colour on a webpage using the setInterval() function.
     
  • Real-time data updates: The setInterval() function can be used to periodically fetch data from a server or API and update the application's user interface (UI) with the new information.
     
  • Timer countdowns: setInterval() can be used to decrement a timer countdown that is displayed on a webpage at regular intervals until it reaches zero.
     
  • Chat programmes: setInterval() can be used to periodically check for new messages in a chat programme and update the UI with them.
     
  • Games: The setInterval() function can be used to move objects, detect collisions, and repeatedly update the game state.
     
  • Audio and video players' progress bars can be updated at predetermined intervals by using the setInterval() function.
     
  • Automatic slide shows: By repeatedly changing the displayed image after a predetermined interval, setInterval() can be used to create automatic slide shows on a webpage.

 

Must Read Fibonacci Series in JavaScript

Frequently Asked Questions

What does the javascript setInterval() method do?

When a function is repeated repeatedly, like animations, the setInterval() function is commonly used to set a delay. After a fixed interval of time, the function begins to execute, and at that point, it repeats the function call continuously.

Can we pause setInterval in JavaScript?

No, setInterval cannot be paused directly in JavaScript. However, you can simulate a pause by using clearInterval to stop it temporarily and then restart it using another setInterval when needed.

How do you cancel a setTimeout or setInterval in JavaScript?

To cancel a setTimeout or setInterval, you use the clearTimeout or clearInterval function, respectively, and pass the ID returned when the timer was initially set.

What is setTimeout and setInterval in JavaScript?

setTimeout executes a function after a specified delay, while setInterval repeatedly executes a function at set intervals until explicitly stopped using clearInterval. Both functions are used for timed execution in JavaScript.

Conclusion

In this article, we explored the setInterval() function in JavaScript, understanding its role in executing code at specified intervals. We discussed how it works, its syntax, and practical examples to help implement repeated actions in web applications. Proper use of setInterval() ensures efficient and responsive execution of timed tasks.

In this article, we extensively discussed the javascript setInterval() function. 

We hope this blog has helped you with your interview. We recommend you visit our articles on different topics of Javascript, such as

Live masterclass