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.
The setInterval method executes specified function or piece of code at a given time interval.
setInterval(function, milliseconds, arg1, arg2, ...)
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 cancels the code to be execute set in setInterval method.
clearInterval(setIntervalVariable)
setIntervalVariable
is the variable defined for setInterval method.This is useful to stop executing code set in setInterval method.
<!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.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on harsukh21@gmail.com
Customizable Checkbox and Radio Buttons using iCheck jQuery plugin
While creating simple html form, there a...How To Install Pip3 On Ubuntu 20.04
PIP is python package manager that insta...How to Build a Chrome Extension
Extensions in Google chrome and Add-ons...How to Count Number of Rows in a Table Using jQuery
Use the length Property You can simpl...How to replace character inside a string in JavaScript
Use the JavaScript replace() method Y...