January 15, 2009

Javascript: setInterval() - call a function every X seconds

setInterval() is used when you want a function to run repeatedly on a timer. I wrote this little html page to remind me to get up and stretch every half-hour. I keep it open in my browser during the day to keep me from slouching for too long. Programming for hours on end can lead to Repetitive Strain Injuries in the hands and arms (amongst other problems), so this could help you too :)

setInterval ( "tellMeToGetUp()", 1000 * 60 * 30 );
function tellMeToGetUp()
alert('GET UP DUDE!');
Note the time passed into the setInterval function. It means: 1000 milliseconds x 60 seconds x 30 minutes. setInterval uses milliseconds, so this is a clear way to describe how long you want the interval to be.

No comments:

Post a Comment