Helping ordinary people create extraordinary websites!
   

JavaScript timer using JavaScript SetTimeout and SetInterval

Tuesday, 1st December 2009
by Omar

There are a few things I would like to add to my website that will need to be run on specific time intervals. What I need to know is how I can setup timed scripts on my website using JavaScript. I was told to check out the setTimeout or setInterval functions. I appreciate any help.

Thanks.


Tags:

stuart
There are three main functions for handling intervals in JavaScript; setInterval, clearInterval and setTimeout.


If you want something to happen every second for example you could do this:
setInterval(function() {
// Add your code here
}, 1000);

The 1000 is how many milliseconds it should wait before running again. 1000 milliseconds => 1 second.

If you want to stop a setInterval from running again then you can do this:

// Run 5 times then stop
var i = 0,
timer = setInterval(function() {
document.write('Run ' + i + ' times');
if( i == 5 ) {
window.clearInterval(timer);
}
}, 1000);


The last function is if you want to run a function in a second for example but only once.

// Run this function in 5 seconds
setTimeout(function() {
// Your Code
}, 5000);



Hope this helps!
Thursday, 17th December 2009
Votes:
16
9

More JavaScript Help:
» How can I round to x decimal places in JavaScript?
» When a form contains a field called action. How do you access the actual form.action?
» Preloader gif or adsense that appears before the game loads
» How can I create a select all link for my text area with JavaScript?
» How can I create Facebook applications?
» How to validate the textbox value in html
» Displaying content by using checkboxes with Java Script
» How to populate fields on a web form from a separate program.