How to use setInterval() in JavaScript?

This article shows you a complete understanding of the setInterval() method and its uses in Javascript.

The setInterval() is a method available in the window object. It is a global method, that can be called from anywhere. The setInterval() method, repeatedly calls a function or executes a piece of code, with a fixed time delay(in milliseconds) between each call.

Let’s see a few examples of the setInterval() method below:-

Example1 (Background change)

Example2 (Digital watch)

What is setInterval()?

The setInterval() is a global method that executes a callback function or executes a piece of code repeatedly in a specified time interval(in milliseconds).

This method returns an interval ID that uniquely identifies the interval, so we can remove it later by calling clearInterval() method.

Note: 1000 milliseconds = 1 second.


var intervalID = setInterval(function, milliseconds, arg1, arg2, …);


function –

A callback function is to be executed every specified delay time.

milliseconds [optional]-

The time, in milliseconds that the timer should wait before the specified function to be executed. This is an optional parameter. If this parameter is omitted, a value of 10 is used.

Note: The delay argument is converted to a signed 32-bit integer. This effectively limits delay to 2147483647 ms.

arg1, arg2, … [optional]-

Additional arguments are passed through to the function specified by the function. These arguments are also optional.

Return value

The returned intervalID is a positive integer value that identifies the interval created by the call to setInterval(). This value can be passed to clearInterval() to cancel the interval.

The setInterval uses in Javascript

The followings are a few examples of using the setInterval method in javascript:

Example-1: Displaying count value every 2 seconds interval.

// displaying count in every 2 seconds interval
var count=1;
      console.log("count=> "+count++);
}, 2000);

//Output in browser console:

//count=> 1
//count=> 2
//count=> 3

Example-2: Passing the additional parameters to setInterval()

// Here messages will be displayed in each 3 seconds

      console.log("Received parameters value :"+arg1+", " +arg2);
}, 3000, "param1", "param2");

//Output see in browser console:

//Received parameters value :param1, param2
//Received parameters value :param1, param2

Example-3: Showing a digital watch

<p id="digital-watch">00:00:00</p>
setInterval(function() {
  const date = new Date();
  document.getElementById("digital-watch").innerHTML = date.toLocaleTimeString();
}, 1000); 


Clearing the setInterval()

The global clearInterval() method clears or cancels an interval previously established by calling setInterval(). The setInterval method returns an intervalID (an integer value) which is used by the clearInterval() method to clear the interval.

For example: Changing the background color of a box in 1 second of the interval with a specified list of colors. And on the stop button click, stopping the color change.

<p>Changing background color of box</p>
<div id="box1" style="height:100px;width:100px;background:orange;margin-bottom:10px;"></div>
<button onclick="start()">Start</button>
<button onclick="stop()">Stop</button>
var count=0;
    var intervalId=null;
    var colors=['red','green','yellow','blue','orange'];
    function start(){ 
          var box1=document.getElementById('box1');
function stop(){ 
    intervalId =null;

//starting by default


Changing background color of box

How to execute setInterval() without delay for the first time?

The functionality of the setInterval() method is to execute a function or piece of code repeatedly at a specified delay. So for the first time also it takes a specified delay time to execute.

Now, let’s see a few solutions to execute the setInterval method without delay for the first time:

Solution#1: Using IIFE (Immediately-invoked Function Expression)

The IIFE is a type of function that immediately gets invoked after its declaration. With the help of this, the setInterval() executes function without a delay for the first time.

For Example:

<p id="demo"></p>
  let count=1;
  setInterval(function displayCount() {
      return displayCount;
  }(), 3000);

//display the count immediately without waiting for 3 seconds first time

Solution#2: Calling method one time before executing setInterval

Define the logic inside a method and call that method once before executing setInterval. This will execute the function once immediately and then the setInterval() function can be set with the required callback function.

For Example:

<p id="demo"></p>
let count=1;
function displayCount(){
//calling this method once before setInterval
}, 5000);

//display the count immediately without waiting for 5 seconds first time

How to change the time interval of setinterval() at runtime?

Once the interval has been created there is no chance to change its interval time at runtime. But if we clear the previous interval and create a new interval with a new time delay it’s possible to do.

Solution#1: Using clearInterval() method

We have to clear the previously created interval whenever we need to change the interval time. To clear the interval, interval ID needs to be passed which is returned by setInterval() method.

For Example:

<p id="demo"></p>
<button onclick="updateIntervalTime()">Update</button>
var count=1;
var delay=1000;//1 sec
var intervalID=null;
function displayCount(){
   }, delay);
//first time calling

function updateIntervalTime(){
    //increasing delay time by 1 second
    delay = delay + 1000;

setInterval() vs setTimeout() in Javascript

The following table describes the basic difference between setInterval and setTimeout methods:

DefinitionThe setInterval() method executes a callback function or executes a piece of code repeatedly in a specified time interval(in milliseconds). The setTimeout() method executes a callback function or executes a piece of code only once after a specified time delay(in milliseconds).
Syntaxvar intervalID = setInterval(function, milliseconds, arg1, arg2, …);var timeoutID = setTimeout(function, milliseconds, arg1, arg2, …);
Default delay ( milliseconds)The milliseconds argument is optional. if this is omitted, a default value of 0 will be used.Here also milliseconds argument is optional. The default value 10 will be used when it is omitted.
Example//print count value every 1-second interval

var count=1;
console.log(“count = “+count++);
//message will display only one time after 2 seconds delay

alert(“Hello world!”);
Stopped byUsing clearInterval() method, it can be stopped.Using clearTimeout() method, it can be stopped.


In this article, you have seen how do we use the setInterval() method in javascript. Learn more about setInterval() method.

See few application programs created using setInterval() method,


What is the return value of setInterval?

The setInterval() returns a positive numeric value(intervalID) that identifies the created interval. You can pass the intervalID to the clearInterval() to cancel the timeout.

How do you break setInterval?

The clearInterval() method is used to break the setInterval() by passing the interval ID which is created by calling the setInterval() method.

Is it bad to use setInterval?

In the case of time-intensive synchronous operations, setInterval may break the rhythm. Also, if any error occurs in the setInterval code block, it will not stop execution but keeps on running faulty code. Alternatively, you can use setTimeout recursively in case of time-sensitive operations.
know more

Related Articles:

You may also like:

Share with friends

Leave a Comment

Your email address will not be published. Required fields are marked *