JavaScript setInterval()

On the Window and Worker interfaces, the setInterval() method calls a function or executes a snippet with a specified time delay between each call.

This function provides an interval ID that uniquely identifies the interval, allowing you to clear it afterward using clearInterval ().

1000 milliseconds equal 1 second

Syntax

setInterval(function, milliseconds, param1, param2, ...)

Parameter Values

  function  Required  A function that will be run per millisecond of delay. After milliseconds of delay, the first execution occurs.  
  milliseconds  Optional  The timer should wait in milliseconds before the provided function or code is run. If this option is set less than 10, a value of 10 is used, which means that the event will be executed with an interval of 10 milliseconds.  
  param1, param2, param3 ...  Optional  Additional parameters are given through to the function that the function specifies.  

Return Value

The intervalID value provided by setInterval() is a non-zero numeric integer that identifies the timer generated by the function; this value may be supplied to clearInterval() to cancel the interval.

It's worth noting that setInterval() and setTimeout() both use the same pool of IDs, and that clearInterval() and clearTimeout() are technically interchangeable. To minimize confusion while maintaining the code, we should aim to match them as much as possible.

The delay parameter is transformed to a signed 32-bit integer before being used. Because it's stated as a signed integer in the IDL, this effectively limits delay to 2147483647 ms.

Example

 setInterval(myTimer, 1000);


function myTimer() {
 	 const date = new Date();
	document.getElementById("demo").innerHTML = date.toLocaleTimeString();
}

Why not setInterval?

To understand why setInterval is bad, remember that JavaScript is fundamentally single-threaded, which means it can only do one action at a time. When functions take longer than the delay specified in setInterval (for example, an ajax call), we'll see that either function doesn't have enough breathing room or setInterval() breaks its rhythm.

In the event of asynchronous actions, setInterval will result in a large backlog of requests, which is inefficient. When performing time-consuming synchronous tasks, setInterval may disrupt the flow. If there is an issue in the setInterval code block, it will not stop the execution but will continue to run the defective code. They also require a clearInterval function to put an end to it. In the event of time-sensitive actions, you may also use setTimeout recursively.

In JavaScript, how can I call the setInterval method for the first time without delay?

The setInterval() method uses one of two mechanisms to call the function after the delay for the first time:

Firstly, perform a single call to the function before running setInterval. Before utilizing the setInterval method, the function can be called once. This will instantly execute the function, allowing the setInterval() method to be used with the needed callback.

A new function is constructed that first encloses the function's invocation and then calls the setInterval() method. For the first time, this will assist in simulating the setInterval() method without a wait.

Secondly, inside the setInterval function, use an instantly calling function. An Immediately-invoked Function Expression (IIFE) is a function that is invoked right after it is declared. This property can be utilized in the setInterval() function's callback since it will be run once, and then the real setInterval() will commence after the provided delay. For the first time, this will aid in simulating the setInterval() method without a wait.

How to stop setInterval?

A timer set with the setInterval() function is cleared using the clearInterval() method. The global clearInterval() function eliminates a timed, recurring action that was previously performed using the setInterval() method ().

Syntax

clearInterval(intervalID)

intervalID - The identification of the activity you want to stop repeating. The equivalent call to setInterval returned this ID ().

It's important to note that the pool of IDs used by setInterval() and setTimeout() are the same, therefore clearInterval() and clearTimeout() may potentially be used interchangeably. However, for the sake of clarity, you should refrain from doing so.

Difference between setTimeout() and setInterval()?

JavaScript timing events include setTimeout and setInterval. The setTimeout method delays the execution of a function, whereas setInterval repeatedly calls a function with a delay between each call.

Please keep in mind that no scheduling approach can ensure an accurate delay. The in-browser timer, for example, may slow down for a variety of reasons:
•  The processor is overworked.
•  The browser tab has been switched to the background.
•  The laptop is powered by a battery.

Summarizing

  • The setInterval() method in JavaScript runs a given function several times at specified millisecond intervals (1000ms = 1 second).
  • Until the clearInterval() method is performed, or the window is closed, the JS setInterval() method will keep calling the provided function.
  • The setInterval() function in JavaScript produces an ID that may be used by the clearInterval() method to terminate the interval.
  • Use the setTimeout() method if you need to run a function once.



ADVERTISEMENT
ADVERTISEMENT