Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Scheduling a Call in JS
3.
Javascript SetInterval()
3.1.
Parameters
4.
Examples
4.1.
Example 1: Display a Message
4.2.
Example 2: Display a dialogue box
4.3.
Example 3: Digital Clock
5.
Alternative to Javascript SetInterval()
6.
Garbage Collection
7.
Application of setInterval() in Javascript
8.
Frequently Asked Questions
8.1.
What does the javascript setInterval() method do?
8.2.
How can I stop my setInterval() function?
8.3.
What type of time measure does the setInterval () function use?
9.
Conclusion
Last Updated: Mar 27, 2024
Easy

setInterval( ) in JavaScript

Author Nidhi Kumari
1 upvote

Introduction

Have you ever found yourself in a situation where you must execute a function after a fixed interval? Computer Science makes our lives easy. There are so many time-based apps in JS that can help you to decide the execution time of a function or a program. 

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.

Scheduling a Call in JS

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.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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.

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

const timerId = setInterval(function, [interval], [arg1], [arg2], ...)

 

Parameters

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

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>

 

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>

 

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>

 

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);

 

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. 

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);

 

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.

How can I stop my setInterval() function?

If you want to stop the function call of your javascript setInterval() function, you can use the clearInterval() function. The syntax for the clearInterval function is clearInterval(interval_ID). Here interval_ID is a positive number returned by the javascript setInterval() method. 

What type of time measure does the setInterval () function use?

The setInterval() method executes a function at predefined intervals(in milliseconds). Until clearInterval() is called or the window is closed, the setInterval() method keeps running the function. 

Conclusion

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

If you liked our article, do upvote our article and help other ninjas grow.  You can refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingSystem Design, and many more!

Head over to our practice platform Coding Ninjas Studio to practise top problems, attempt mock tests, read interview experiences and interview bundles, follow guided paths for placement preparations, and much more!!

Happy Reading!!

Previous article
JavaScript scopes, closures
Next article
JavaScript onload
Live masterclass