setInterval JavaScript

What is setInterval?

setInterval is a JavaScript method that executes a specified function at set time intervals. This function continues to run until it is stopped or the webpage is closed. Common uses include updating a timer, refreshing a webpage, or running animations. It takes two parameters: the function to be executed and the time interval in milliseconds.

Why is it important?

To stop a recurring function, use the clearInterval method. This prevents memory leaks and optimizes performance. Here's how to use it:

1. Create a variable to store the interval ID:

let intervalID = setInterval(function, milliseconds);

2. Call clearInterval to stop the recurring function:

clearInterval(intervalID);

Using clearInterval ensures that resources are freed up, which is crucial for long-running applications or those with multiple recurring functions.

Using the setInterval Method

Syntax of setInterval

The syntax of the setInterval method is:

setInterval(function, delay)

  • function: The function to be executed at each interval.
  • delay: The time (in milliseconds) between each execution.

setInterval returns a unique identifier for the interval, which can be used to clear or cancel the interval using clearInterval. Additionally, you can pass arguments to the function after the delay parameter:

setInterval(function(arg1, arg2), delay, arg1, arg2);

How to Use setInterval for Timing Events

Define the function you want to repeat, then use setInterval() to set up the timing. For example, to create a clock that displays the time every second:

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

Understanding Time Intervals

Defining Time Interval

Specify the duration and interval frequency for a recursive setTimeout() pattern to ensure the previous interval completes before recursing:

function myFunction() {
  // code to be executed
  setTimeout(myFunction, intervalFrequency);
}
myFunction();

Specifying Time Interval in Milliseconds

Pass the desired interval in milliseconds as the second argument to setTimeout():

setTimeout(myFunction, 1000);

For continuous repetition, use a recursive setTimeout() pattern. Note that the default minimum interval is 10 milliseconds.

Working with Current Time

Retrieving Current Time Using JavaScript

Use the Date object to get the current time:

let currentDate = new Date();
let currentHour = currentDate.getHours();
let currentMinute = currentDate.getMinutes();
let currentSecond = currentDate.getSeconds();

Using Current Time with setInterval

To create a clock that updates every second:

function updateClock() {
  let now = new Date();
  let hours = now.getHours();
  let minutes = now.getMinutes();
  let seconds = now.getSeconds();
  console.log(`${hours}:${minutes}:${seconds}`);
}
setInterval(updateClock, 1000);

Additional Arguments in setInterval Method

Adding Additional Parameters to the Callback Function

Three ways to add additional parameters to the callback function:

1. Directly in setInterval:

setInterval(callback, delay, arg1, arg2);

2. Using an anonymous function:

setInterval(function() { callback(arg1, arg2); }, delay);

3. Using bind:

setInterval(callback.bind(null, arg1, arg2), delay);

Clearing Intervals with clearInterval Method

To clear intervals, use the clearInterval method with the interval variable:

let intervalID = setInterval(myFunction, 1000);
clearInterval(intervalID);
Written by

Master JavaScript by choosing your ideal learning course

View all courses

Create a free account to access the full topic

Sign up with Google
Sign up with Google
Sign up with JetBrains
Sign up with JetBrains
Sign up with Github
Sign up with GitHub
Coding thrill starts at Hyperskill
I've been using Hyperskill for five days now, and I absolutely love it compared to other platforms. The hands-on approach, where you learn by doing and solving problems, really accelerates the learning process.
Aryan Patil
Reviewed us on