Execute a Function at Regular Intervals using JavaScript

The Window.setInterval() contains two parameters: the function name/function call with parameters and the time of the timer. Using this, you can execute a function at regular intervals. Here’s a small example:

<html xmlns="http://www.w3.org/1999/xhtml" >
<
head>
<
title>Run the Same Function at Regular Intervals w/ JavaScript</title>
<
script type="text/javascript">
var cnt = 0;
setInterval(printDuration, 3000);
function printDuration() {
cnt += 1;
document.getElementById("para").innerHTML = cnt;
}
</script>
</
head>
<
body>
<
div>
<
p id="para">0</p>
</
div>
</
body>
</
html>

As you can see, we have set a timer of 3000 millisecond or 3 seconds. The printDuration() gets called after every 3 seconds and by manipulating the paragraph (para) element’s innerHtml , we are able to print the value of the counter in it.

Update: You may also want to look at Start and Stop a Timer in JavaScript

See a Live Demo



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: