JavaScript setInterval
Posted by Superadmin on May 03 2023 02:32:25

JavaScript setInterval

By Payal UdhaniPayal Udhani
  

JavaScript setInterval

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:

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:

JavaScript setInterval 1

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:

setintrvl ex2

set interval 2.1

setinterval 2.3

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:

passing argument

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.

start displaying

Callback Arguments

var argumentPassingIntervalId = setInterval(function() {
mainFunction('param1', 'param2', 'param3');
}, 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:

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.