JavaScript setInterval() Complete Tutorial

In this section, we will learn what the setInterval() function is and how to use it in JavaScript.

Note: we’re assuming you’re already familiar with the `setTimeout()` function.

What is setInterval() Function in JavaScript?

When we want to run a set of instructions periodically (for example every 60 seconds), we can use the `setInterval()` function.

Just like the `setTimeout()`, this function also is a Web-API. This means the execution engine only runs this function once and after that, the program that is behind the `setInterval()` will periodically send the request of executing the target function to the queue. After that, every time the execution engine receives this request from the queue, it will invoke the body of the target function into the stack and execute its instructions.

setInterval() Function Syntax:

Here’s the structure of this function:

setInterval(function, time, parameter1, parameter2, …);

`function`: This is the target function that we want it to be executed periodically.

`time`: The second argument, which is the time, defines how often we want the target function to be executed.

Note: the time is on millisecond. Basically, one second is equal to 1000 milliseconds. So if we want to execute the target function like every 5 seconds, we need to set the second argument to 5000 milliseconds, which is equal to 5 seconds.

`parameter1, parameter2,…`: if the target function takes arguments as well, we can put those arguments after the second argument. So when the execution engine starts to execute the target function, it will pass these arguments to that function.

The return value of this function is an ID of type number that can be used in the `clearInterval()` function to cancel the timer.

Example: using setInterval() function in JavaScript

function sayHi(name){
  console.log(`Hello ${name}`);
const id = setInterval(sayHi, 2000, "John Doe"); 


Hello John Doe

Hello John Doe


How Does JavaScript setInterval() Function Work?

The message `Hello John Doe` will appear on the browser’s console every 2 seconds.

This is because of the second argument to the `setInterval()` function is set to 2000 milliseconds (which means every 2 seconds).

JavaScript clearInterval() Function: (Stop setInterval in JavaScript)

We can stop a call to the setInterval() function before it being executed or during its execution time. This is done via a call to the clearInterval() function.

In the clearInterval() function, we’ve explained this function in great details.


Top Technologies