Javascript setInterval() run a function repeatedly by fixed time interval

Introduction

Use the JavaScript setInterval() method to run a function repeatedly after a certain time period.

The setInterval() method requires two parameters:

  • a function or an expression
  • time delay in milliseconds.

View in separate window

<!DOCTYPE html>
<html lang="en">
<head>
<title>Calling a Function Repeatedly with setInterval() Method</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
var myVar;// w w w.  ja v a 2 s . c om
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);// one second, 1000 milliseconds
});
</script>
</head>
<body>
    <p id="demo"></p>
    <button onclick="stopFunction()">Stop Timer</button>
</body>
</html>



PreviousNext

Related