Timing events in javascript helps to execute a function, after a specified time interval.
setTimeout() – Executes a code some time in the future.
clearTimeout() – Cancel an existing setTimeout event.
var somevariable = setTimeout("function_to_execute",milliseconds);
clearTimeout(somevariable)
Here is sample code snippet for a Javascript counter using SetTimeout and ClearTimeout functions.
Timing events in javascript helps to execute a function, after a specified time interval.
setTimeout() – Executes a code some time in the future.
var somevariable = setTimeout(“function_to_execute”,milliseconds);
clearTimeout() – Cancel an existing setTimeout event.
clearTimeout(somevariable)
Code of a javascript counter.
<html>
<head>
<title>Javascript counter</title>
<script type="text/javascript" language="Javascript">
var var_counter = 0;
var var_timer;
function start_counter() {
document.getElementById("counter").innerText = var_counter;
var_counter++; var_timer = setTimeout("start_counter()", 1000);
}
function stop_counter() {
clearTimeout(var_timer);
}
</script>
</head>
<body>
Counter :
<div id="counter">
</div>
<br />
<button onclick="start_counter()">
Start</button>
<button onclick="stop_counter()">
Stop</button>
</body>
</html>
if var_counter variable is local scope instead of global, every time clicking on start button will initialize the counter.
There is two more timing related functions available in Javascript.
SetInterval() and ClearInterval() – It is almost same as the SetTimeout and clearTimeout, only difference is setTimeout() triggers expression only once, setInterval() keeps triggering expression again and again (unless you tell it to stop). And the Syntax are same. You can write the counter with SetInterval very easily that setTimeOut