setInterval()
methodYou can use the JavaScript setInterval()
method to execute a function repeatedly after a certain time period. The setInterval()
method requires two parameters first one is typically a function or an expression and the other is time delay in milliseconds.
In the following example the showTime()
function is called repeatedly after every 1000 milliseconds (i.e. 1 second) until you tell it to stop. Let's try it out and see how it works:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>The JavaScript setInterval() Method</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
var myVar;
function showTime(){
var d = new Date();
var t = d.toLocaleTimeString();
$("#demo").html(t); // display time on the page
}
function stopFunction(){
clearInterval(myVar); // stop the timer
}
$(document).ready(function(){
myVar = setInterval("showTime()", 1000);
});
</script>
</head>
<body>
<p id="demo"></p>
<button onclick="stopFunction()">Stop Timer</button>
</body>
</html>
However, a better approach is using the setTimeout()
function if you are doing some time consuming stuff. Because, unlike the setInterval()
with setTimeout()
function you can wait till function is executed completely before calling it again. Here's an example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>The JavaScript setTimeout() Method</title>
<style>
img{
display: none;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
var myVar;
function showImage(){
$("img").fadeIn(750).fadeOut(750);
myVar = setTimeout(showImage, 2000);
}
function stopFunction(){
clearTimeout(myVar); // stop the timer
}
$(document).ready(function(){
showImage();
});
</script>
</head>
<body>
<button onclick="stopFunction()">Stop Image Transition</button>
<p>
<img src="images/sky.jpg" alt="Cloudy Sky">
</p>
</body>
</html>
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 [email protected]
How to stop firing event until an effect is finished in jQuery
Use the jQuery callback function You...Repair grub after Installing Windows on Preinstalled Ubuntu
You might want to use Windows and Ubuntu...Laravel Dynamically Add or Remove Input Fields jQuery
In this article, we will share with you...Google Maps JavaScript API Get Travel Distance Between Points
In the process of getting distance betwe...Laravel CRUD with Vue Router and Sweet Alert
In this tutorial, i am going to engender...