×

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

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 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.

Synchronous and Asynchronous in JavaScript

JavaScript is a powerful and versatile language that is used all over the web, from small websites to large applications. It is essential for developers to understand the differences between...

9 minutes 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 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.

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.

JavaScript moment date difference

Often date differences are required on the web platforms for various reasons. They can be: To find the duration, of course, someone is pursuingTo find the age of a user from...

7 minutes read.

JavaScript radio button checked value

What are radio buttons? A radio button is defined as an icon that is used to take input from the user. The user can choose only one option(value) from the group...

5 minutes read.

Javascript Password Validation

Here we see that how to validate any password field. Like password field can be blank and length of password is minimum 8 characters. Example <!DOCTYPE html>   <html>   <head>   <script>   functionpass_validation()   {     var password=document.myform.password.value;     if (password==null || password=="")   {     alert("password can't be blank");     return false;     }   else if(password.length<8)   {     alert("Password must be at least 8 characters long.");     return false;       }     }     </script>   </head>   <body>   <form name="myform" method="post" action="register.php" onsubmit="return pass_validation()" >   Password: <input type="password" name="password">   <input type="submit" value="submit">   </form>   </body>   </html> Try Now ← Prev Next → ...

1 minute read.

Javascript input maxlength

Various attributes often accompany the input tag in HTML to change the properties of the input field. Maxlength() is one such attribute. The maxLength attribute defines the maximum number of characters...

2 minutes read.

Javascript Date

In JavaScript Date Object is data type build into the JavaScript language. Data object are created with the new Date(). JavaScript Date instance that represents a single moment in time. JavaScript...

2 minutes read.

Javascript Math

Math is build-in object that has properties and methods for mathematical constants and functions. It allows you to perform mathematical tasks on numbers. Syntax varpi_val = Math.PI; varsin_val = Math.sin(30); Examples Math.pow() Math.pow(x,y) returns the value of x to the power...

2 minutes read.

Javascript Window Object

The window object represents a window in browser. An object of window is created automatically by the browser. Window is the object of browser, it is not the object of JavaScript. The...

3 minutes 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 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.

JavaScript p5.js

Introduction to p5.js P5.js is a JavaScript library for creative programming. It is built on Processing, a coding environment for creativity. Processing's major goal is to make it as simple as...

4 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.

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 getElementByID

The document.getElementById() method returns the element of specified id. In below example we receive input field by using document.getElementById() method, here document.getElementById() receive input value on the basis of input field...

1 minute read.