Sometimes you might want to run function or piece of code at the specific time interval. This is mostly used when you want to update data at a given time or want to refresh page.
In this example, I will explain how you can execute Javascript code at the specific time interval. I will also include how you can stop this interval to run code.
setInterval method
The setInterval method executes specified function or piece of code at a given time interval.
Syntax
setInterval(function, milliseconds, arg1, arg2, ...)
Where:
function
which executes at a given specific time.
milliseconds
is time interval
arg1, arg2
parameters pass in the function.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>setInterval method</title>
</head>
<body>
<div id="number">0</div>
<script type="text/javascript">
setInterval(function() {
var data = document.getElementById('number').textContent;
document.getElementById('number').textContent = Number(data) + 1;
}, 1000);
</script>
</body>
</html>
clearInterval method
clearInterval method cancels the code to be execute set in setInterval method.
Syntax:
clearInterval(setIntervalVariable)
Where:
setIntervalVariable
is the variable defined for setInterval method.
This is useful to stop executing code set in setInterval method.
Example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>clearInterval method</title>
</head>
<body>
<div id="number">0</div>
<button onclick="increment()">Start</button>
<button onclick="stopIncrement()">Stop</button>
<script type="text/javascript">
var startIncrement;
function increment() {
startIncrement = setInterval(function() {
var data = document.getElementById('number').textContent;
document.getElementById('number').textContent = Number(data) + 1;
}, 1000);
}
function stopIncrement() {
clearInterval(startIncrement);
}
</script>
</body>
</html>
So far in this article, we have learn how to execute Javascript code at a specific interval time. We have also learned to prevent executing code set in setInterval method. I hope you liked the article.