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, 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.

No comments: