Bluefire Bluefire - 1 year ago 135
Javascript Question

JavaScript: get code to run every minute

Is there a way to make some JS code be executed every 60 seconds? I'm thinking it might be possible with a

loop, but is there a neater solution? JQuery welcome, as always.

Answer Source

Using setInterval:

setInterval(function() {
    // your code goes here...
}, 60 * 1000); // 60 * 1000 milsec

The function returns an id you can clear your interval with clearInterval:

var timerID = setInterval(function() {
    // your code goes here...
}, 60 * 1000); 

clearInterval(timerID); // The setInterval it cleared and doesn't run anymore.

A "sister" function is setTimeout/clearTimeout look them up.

If you want to run a function on page init and then 60 seconds after, 120 sec after, ...:

function fn60sec() {
    // runs every 60 sec and runs on init.
setInterval(fn60sec, 60*1000);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download