Open In App

setInterval() function in JavaScript

Last Updated : 12 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The setInterval function in JavaScript is used for repeatedly executing a specified function or code block at fixed intervals. It can be used for creating periodic tasks, animations, and real-time updates in web applications.

It is essential to note that intervals set by setInterval are not guaranteed to be precise due to the single-threaded nature of JavaScript and potential delays in the event queue. The actual interval may be longer if the callback function takes significant time to execute.

setInterval requires caution to prevent potential issues like overlapping intervals and resource consumption. Clearing intervals using clearInterval is crucial to stop repetitive execution when it’s no longer needed, preventing memory leaks.

Syntax:

setInterval(callback, delay);
  • callback function: This is the function that is executed after a regular interval of time.
  • delay: The time, in milliseconds, between each execution of the callback function.

In this instance, the callback function logs an iteration message to the console every second. The setInterval function returns an interval ID, which can be utilized to stop the repeated execution using clearInterval(intervalId).

Example: To demonstrate the counter increase after a fixed regular interval of time.

Javascript




let count = 0;
const intervalId = setInterval(() => {
  console.log(`Iteration ${count}`);
  count++;
}, 1000);


Output:

Peek-2024-02-08-15-47

Increasing counter after regular interval


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads