×

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.

Related Topics

Design a BMI calculator using JavaScript

BMI calculator BMI stands for Body Mass Indicator. It is a numeric value which is calculated based on the height and weight of a person. It represents the fatness of the...

4 minutes read.

Array to String in JavaScript

As a web developer, you often have to deal with multiple data types in a single application. How to convert an array to a string in JavaScript is essential for...

19 minutes read.

What is Ternary Operator in JavaScript?

In some cases, a ternary operator can be used instead of an if-else expression. A ternary operator examines a condition and then runs a block of code in response to...

4 minutes read.

Javascript Cookies

Cookie is a piece of data which is sent from a website and stored locally by the user's browser. Cookie is needed because HTTP is stateless protocol. Today most of...

1 minute read.

JavaScript focus on input

In JavaScript, the elements can be focused using either focus() method or onfocus() event. What is focus() method? When we want to focus on an element (if it can be focused) or...

4 minutes read.

Javascript Email Validation

We can validate the email with the help of JavaScript. Here we check the condition related to any email id, like email it must have "@" and "." sign and...

2 minutes read.

JavaScript setTimeout()

The setTimeout() method creates a timer that, when it expires, runs a function or provides a piece of code. setTimeout() is an asynchronous function, which means that it will not interrupt...

3 minutes read.

JavaScript Function

An important part of JavaScript is the ability to create new functions within <script>.....</script> tag. To declare a function in JavaScript using function keyword. We call JavaScript function multiple times to reuse the...

3 minutes read.

JavaScript Arrays

JavaScript Arrays: JavaScript Arrays are a type of variables that allows us to store the individual or the group of values under a single variable. What is an Array in JavaScript? The array...

6 minutes read.

Javascript If Else

Introduction The if-else statement is an important control structure for decision-making in code based on some conditions. It gives programmers the ability to add decision-making functionality into their programs. Using if-else,...

6 minutes read.

Javascript Event

Events are things that happen, usually user action, that are associated with an object. All object have properties and methods. Some objects also have events. The event handler is a command that is...

1 minute read.

Javascript Page Redirect

The window.location object can be used to get the current page address (URL) and to redirect browser to new page. In some websites when we visit, we face a situation where we...

3 minutes read.

Javascript Re-Password Validation

Example <!DOCTYPE html>   <html>   <head>   <script>   function pass_validation()   {   var firstpassword=document.f1.password1.value;     var secondpassword=document.f1.password2.value;     if(firstpassword==secondpassword){     return true;     }     else{   alert("Password does Not Match");     return false;     }     }    </script>   </head>   <body>   <form name="f1" action="/JavaScript/Index" onsubmit="return pass_validation()">   Password:<input type="password" name="password1" /><br/>   Re-enter :<input type="password" name="password2"/><br/>   <input type="submit">   </form>   </body>   </html> Try Now ← Prev Next → ...

1 minute read.

JavaScript Image resize before upload

Image resizing can be a quite tedious task, so it is usually done on the server-side. The resized image file is then delivered to the client side. However, sometimes the...

3 minutes read.

Javascript Find Object In Array

What is find() method? It returns the value of the first element in the given array that fulfils the given testing function. However, if no values from the array are able...

3 minutes read.

Javascript String

String object works with series of characters. It is used to store and manipulate text. There are two ways to create string in JavaScript: String literal. Using new keyword. String literal By using double quotes...

4 minutes read.

Javascript Switch Statement

Introduction Conditional statements are simple building blocks in programming languages and are utilized fairly frequently. This portion of Developing Conditional Statements in JavaScript talks about how to utilize the if, else,...

5 minutes read.

Callback and Callback Hell in JavaScript

The widely used client-side programming language JavaScript is simple, light, and interpretive. JavaScript is used by the majority of client-side web applications. It is also possible to use JavaScript on...

3 minutes read.

JavaScript dropdown onchange

What is onchange event? It is an event in JavaScript used to make the web pages dynamic. The onchange event gets triggered whenever the value of an event changes. It usually...

3 minutes read.

Minify JavaScript

What do you mean by the term ‘Minification’? The technique of minification reduces the amount of code and markup in your websites and scripting files. It's one of the most used...

4 minutes read.