Start and Stop a Timer in JavaScript

In one of my previous posts, I had shown how to Execute a Function at Regular Intervals using JavaScript. One of the devcurry.com readers ‘Marjidk’ commented asking if it was possible to stop the timer manually. Well the answer is yes and it is quite simple. I will be using an anonymous function within a setInterval() method for this example to demonstrate how to start and stop a function execution. Let us see the code first.

<html xmlns="http://www.w3.org/1999/xhtml" >
<
head>
<
title>Start and Stop a Timer using JavaScript by DevCurry.com</title>
<
script type="text/javascript">
var
check = null;

function printDuration() {
if (check == null) {
var cnt = 0;

check = setInterval(function () {
cnt += 1;
document.getElementById("para").innerHTML = cnt;
}, 1000);
}
}

function stop() {
clearInterval(check);
check = null;
document.getElementById("para").innerHTML = '0';
}
</script>
</
head>
<
body>
<
div>
<
p id="para">0</p>
<
input id="btnStart" type="button" value="Start"
onclick="printDuration();" />
<input id="btnStop" type="button" value="Stop"
onclick="stop();" />
</div>
</
body>
</
html>

There is an advantage in using an anonymous function here within a setInterval() method. Observe that we are using a variable ‘cnt’ local to the printDuration() function, hence there is no need of a Global variable now, as we used in our previous example. When the user hits the Start button, the printDuration() gets executed and gets called after every 1 second, manipulating the paragraph (para) element's innerHtml and printing the value of the counter in it.

Clicking the Stop button clears the timer by using the clearInterval(), passing in the ‘check’ variable that is returned by the call to setInterval(). The last step is to reset the value of the counter to ‘0’.

See a Live Demo






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

1 comment:

Marjidk said...

nice. anyway to stop the loop manually?