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 hide dropdown menu on click outside of the element in jQuery
Use the jQuery on() method You can us...Jupyter Notebook installation in Ubuntu
In this article, we will share with you...Laravel 5.4 - Get comma separated values in sql
Some time you get recird from comma sepa...HTML To PDF In Laravel Using barryvdh/laravel-snappy
Today, laravel code share with you how t...Using Gmail SMTP Server to send Email in Laravel
Follow the below steps to setup email...