Introduction to JavaScript setInterval
The following article provides an outline for JavaScript setInterval. In Javascript, the Window or Worker interface is responsible for providing us the timer events and methods. One of these interfaces’ most important 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: It is the returned value from the setInterval method of WindowOrWorkerGlobalScope scope, 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: It is a function that contains the code snippet that you want to execute repetitively once the interval is set. By default, it is considered that this function should not accept any parameters and should neither return any value.
- DelayTime: It is the time in milliseconds(1 second = 1000 milliseconds) that specifies the time interval between the repetitive call to the function.
- Code: It is a string that can be supplied optionally instead of the function call. This string is compiled and executed each time the setIterval’s delay time is over repetitively. It is generally not used for security reasons.
- Arguments: These are the optional parameters that can be passed to your function call when you require it.
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 feel a necessity to 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 on the ‘Start Displaying’ button, the sample1 element displays the counter, which goes on incrementing and will stop after clicking on the ‘Stop Displaying’ button.
Callback Arguments
- Passing the arguments to the function being called in the setInterval method is not supported by some versions of some browsers.
- 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. There are three ways we can achieve passing arguments to setInterval() for non-compatible browsers.
- 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);
- Here, the main function which passes the arguments is written and called inside the function being passed to setInterval() method.
- Another way of achieving this is by using bind function which can be used in 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. If the setInterval() method is used inside the 5- leveled nested setInterval, it applies the restriction for its delay time of a minimum 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 window scope object for repetitively executing a certain functionality after a certain time interval. However, we must consider certain issues and limitations of this method, like browser compatibility and nesting of such events.