Open In App

setInterval() function in JavaScript

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

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.




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

Output:

Increasing counter after regular interval

Article Tags :