You 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-3.5.1.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:
In the example above the showImage() function is called every time after 2000 milliseconds (i.e. 2 seconds) once the image fade in and fade out transition has been fully completed.
Use the JavaScript
setInterval()
methodYou can use the JavaScript
setInterval()
method to execute a function repeatedly after a certain time period. ThesetInterval()
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: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:
In the example above the showImage() function is called every time after 2000 milliseconds (i.e. 2 seconds) once the image fade in and fade out transition has been fully completed.
need an explanation for this answer? contact us directly to get an explanation for this answer