Updated June 9, 2023
Introduction to JavaScript setInterval
The following article provides an outline for JavaScript setInterval. In Javascript, the Window or Worker interface provides timer events and methods. One of these interfaces’ most essential methods is the setInterval() method. This method allows us to perform or execute a certain code snippet repetitively and after some fixed time interval. It returns a numeric id that uniquely represents the created interval and can be further used to destroy this event or stop repetitive execution with the help of the clearInterval() method and the interval id.WindowOrWorkerGlobalScope mixin provides us with timer-related events. One of them is the setInterval() method.
Syntax of JavaScript setInterval
Given below is the syntax mentioned:
var intervalIdentifier = scope.setInterval(function, delayTime, [arguments1, arguments2, ...]);
var intervalIdentifier = scope.setInterval(code, delayTime);
Explanation:
- Intervalidentifier: The returned value from the setInterval method of WindowOrWorkerGlobalScope scope is a numeric identifier unique for every interval created in the session. It is always non-zero integers and can be further used to stop the execution of interval using the clearInterval() method, which is again, in turn, a method of WindowOrWorkerGlobalScope interface that helps in clearing the interval.
- Function: This function holds the code snippet you aim to execute repeatedly once you set the interval. By default, we assume this function neither accepts any parameters nor returns any value.
- DelayTime: The time in milliseconds(1 second = 1000 milliseconds) specifies the time interval between the repetitive call to the function.
- Code: A string can be supplied optionally instead of the function call. The system compiles and executes this string each time the setInterval’s delay time ends, repeating this process. It is generally not used for security reasons.
- Arguments: You can pass these optional parameters to your function call when needed.
Examples of JavaScript setInterval
Given below are the examples of JavaScript setInterval:
Example #1
Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Demonstration of setInterval() Method</title>
<script>
var intervalIdentifier;
function switchColour() {
intervalIdentifier = setInterval(blinkString, 500);
}
function blinkString() {
var divisionObject = document.getElementById('coloredDivision'); divisionObject.style.color = divisionObject.style.color == 'red' ? 'blue' : 'red';
}
function stopBlinking() { clearInterval(intervalIdentifier);
}
</script>
</head>
<body onload="switchColour();">
<div id="coloredDivision">
<p>Let's Learn setInterval() method usage</p>
</div>
<button onclick="stopBlinking();">Stop</button>
</body>
</html>
Output:
Example #2
Suppose you want to display the countdown for a certain event and display the message after a specific time.
Code:
<!DOCTYPE html>
<html>
<body>
<button onclick="clearInterval(countdownId)">Stop it</button>
<p id="displayCountdown"></p>
<script>
var startCounter=10; //Initialize counter
var countdownId = setInterval(newYearCounter ,1000); function newYearCounter() {
document.getElementById("displayCountdown").innerHTML = startCounter + " Seconds Left!";
startCounter -=1; //decrement counter
if(startCounter===0){
document.getElementById("displayCountdown").innerHTML = "Happy New Year!"; clearInterval(countdownId); //clear the timer once the message is displayed
}
}
</script>
</body>
</html>
Output:
The above countdown will stop if you click to stop it button.
Passing Parameters to the Called Function
There might come a situation in a real-time environment where you must pass the arguments to the function being called. We can optionally pass parameters to the function, which we call repetitively for execution in the setInterval() method.
Code:
<!DOCTYPE html>
<html>
<body>
<p>Demonstration for passing arguments to setInterval method in Javascript</p>
<p>You can click on 'Start Displaying' and 'Stop Displaying' buttons to begin and stop displaying the message</p>
<button onclick="beginDisplayFunc()">Start Displaying</button> <button onclick="stopDisplayFunc()">Stop Displaying</button>
<p id="sample1" style="color:red;"></p>
<p id="sample2" style="color:blue;"></p>
<script>
var intervalId; var counter;
function beginDisplayFunc() {
intervalId = setInterval(function(){ displayMessage("Good", "Morning"); }, 2000); counter=0;
}
function displayMessage(param1, param2) { counter++;
document.getElementById("sample1").innerHTML += counter + " ";
document.getElementById("sample2").innerHTML = "Parameters passed to displayMessage():
<br>"
+ param1 + "<br>" + param2 + "<br>";
}
function stopDisplayFunc() { clearInterval(intervalId);
}
</script>
</body>
</html>
Output:
After clicking the ‘Start Displaying’ button, the sample1 element displays the counter, which goes incrementing and will stop after clicking on the ‘Stop Displaying’ button.
Callback Arguments
- Some versions of some browsers do not support passing arguments to the function called in the setInterval method.
- For example, Internet Explorer’s version 9 and previous versions do not support passing such arguments. In this case, we must make special efforts or consider these exceptions while coding for the setInterval() method. We can achieve passing arguments to setInterval() for non-compatible browsers in three ways.
- Setting isPolyfill property of setInterval() method to true.
- We can use an anonymous calling function to call a function without a parameter in the setInterval() method, which will, in turn, call a function; with we can do so in the following way:
var argumentPassingIntervalId = setInterval(function() {
mainFunction('param1', 'param2', 'param3');
}, 3000);
- In this case, we write and call the main function, which passes the arguments, inside the function that we pass to the setInterval() method.
- Another way of achieving this is by using the bind function, which can be used in the following way – var myIntId = setInterval(function(param1) {}.bind(undefined, 20), 3000);
Nested setInterval() Events
It is possible that we can begin a certain event of setInterval() inside the function, which is, in turn, called by another setInterval() methods call. This is called the nesting of events. Browsers allow the nesting of events for, at most, 5 levels. Using the setInterval() method inside a 5-level nested setInterval enforces a minimum delay time restriction of four milliseconds. If we forcefully specify less than four milliseconds of value browser will internally pin it to 4 milliseconds.
Compatible browsers for this method usage are:
- Chrome 30.0
- Internet Explorer 0
- Firefox 1.0
- Edge
- Opera 0
- Safari 0
Conclusion – JavaScript setInterval
In this way, we can use the setInterval() method of the window scope object for repetitively executing a certain functionality after a specific time interval. However, we must consider certain issues and limitations of this method, like browser compatibility and nesting of such events.
Recommended Articles
This is a guide to JavaScript setInterval. Here we discuss the passing parameters to the called function, callback arguments, and nested setInterval() Events. You may also have a look at the following articles to learn more –