/    /  Javascript-SetInterval

Javascript-SetInterval

 

The setInterval() method in JavaScript provides to repeat a specified function at each given time-interval. It evaluates an expression/calls a function at given intervals. This method continues the calling of function until the window is closed / the clearInterval() method was called. This javascript method was returns a numeric value / a non-zero number that identifies the created timer.

 

Syntax:

 

window.setInterval(function, milliseconds);

 

Parameter values:

 

function: Required. The function that will be executed.

milliseconds: Required. The intervals in milliseconds on how often to execute the block of code. If the value is less than 10, then the value 10 is used.

 

How to stop the execution:

 

You can use the clearInterval() method to stop the execution of the function specified in javascript setInterval() method. The value returned by the setInterval() method can be provided as the argument of clearInterval() method to cancel the timeout.

 

Example:

 

using the setInterval() method.

 

<html> 
<head> 
<title> setInterval() method </title> 
</head> 
<body> 
<h1> Hello World :) :) </h1> 
<h3> This is an example of using the setInterval() method </h3> 
<p> Here, an alert dialog box displays on every three seconds. </p> 

<script> 

var a; 

a = setInterval(fun, 3000); 

function fun() { 
alert(" Welcome to the I2tutorials.com "); 
}</script> 

</body> 

</html>

 

OUTPUT:

 

Javascript-SetInterval

 

Example:

 

Background color will change on every 200 milliseconds.

 

<html>
<head>
<title> setInterval() method </title>
</head>
<body>
<h1> Hello World :) :) </h1>
<h3> This is an example of using the setInterval() method </h3>
<p> Here, the background color changes on every 200 milliseconds. </p>

<script>
var var1 = setInterval(color, 200);

function color() {
var var2 = document.body;
var2.style.backgroundColor = var2.style.backgroundColor == "lightblue" ? "lightgreen" : "lightblue";
}

</script>

</body>

</html>

 

OUTPUT:

 

Javascript-SetInterval

 

Example: 

 

You have not used any method to stop the toggling between the colors.

 

<html>
<head>
<title> setInterval() method </title>
</head>
<body>
<h1> Hello World :) :) </h1>
<h3> This is an example of using the setInterval() method </h3>
<p> Here, the background color changes on every 200 milliseconds. </p>
<button onclick = "stop()"> Stop </button>

<script>
var var1 = setInterval(color, 200);

function color() {
var var2 = document.body;
var2.style.backgroundColor = var2.style.backgroundColor == "lightblue" ? "lightgreen" : "lightblue";
}
function stop() {
clearInterval(var1);
}

</script>

</body>

</html>

 

OUTPUT:

 

Javascript-SetInterval