Javascript Timer Function
Javascript Timer Function
1. setInterval()
2. setTimeout()
1. setInterval Function
The setInterval() method sets a time interval that calls a function or
evaluates an expression at specified intervals (in milliseconds).
setInterval(function, interval)// or
setInterval(code, interval)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Javascript - setInterval</title>
</head>
<body>
<h2>Using "setInterval" method to print next counting after 1 second.</h2>
<p id="output"></p>
<script>
var count = 1;
var element = document.getElementById("output");
function counting(){
element.innerHTML += count + "<br>";
count++;
}
setInterval(counting, 1000);
</script>
</body>
</html>
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Javascript - clearInterval</title>
</head>
<body>
<h2>Using "clearInterval" method to stop printing.</h2>
<button onclick="clearIt()">Clear Interval</button>
<p id="output"></p>
<script>
function clearIt(){
clearInterval(interval); //clearing interval
}
var interval = setInterval(counting, 1000);
var count = 1;
var element = document.getElementById("output");
function counting(){
element.innerHTML += count + "<br>";
count++;
}
</script>
</body>
</html>
2. setTimeout Function
The setTimeout() method calls a function or evaluates an expression after
a specified number of milliseconds.
setTimeout(function, interval) // or
setTimeout(code, interval)
The method contains 2 parameters:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Javascript - setTimeout</title>
</head>
<body>
<h2>Using "setTimeout" method to execute a function after a fixed amount of time.</h2>
<p id="output"></p>
<script>
setTimeout(printTime, 3000);
var element = document.getElementById("output");
function printTime(){
element.innerHTML = new Date();
}
</script>
</body>
</html>
<button onclick="stopIt()">Stop</button>
clearTimeout(timeoutReference);
var timeoutReference = setTimeout();
The setTimeout() method returns a reference that is passed in
the clearTimeout() as an argument to clear timeout.
The following method prints time after three seconds, stopping it from
printing by clearing setTimeout().
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Javascript - setTimeout</title>
</head>
<body>
<button onclick="stopIt()">Stop</button>
<p id="output"></p>
<script>
var ref;
function printTime() {
function stopIt() {
clearTimeout(ref);
function showTime() {
</script>
</body>
</html>
To invoke the function for Use javascript loop, loop for 'n' number of times, and invoke a function in each
'n' number of times iteration
To invoke a function on Use 'addEventListener' method and bind the function with the desired event
some event