[removed] get code to run every minute

前端 未结 2 1325
星月不相逢
星月不相逢 2020-11-28 06:34

Is there a way to make some JS code be executed every 60 seconds? I\'m thinking it might be possible with a while loop, but is there a neater solution? JQuery w

2条回答
  •  余生分开走
    2020-11-28 06:55

    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.
    }
    fn60sec();
    setInterval(fn60sec, 60*1000);
    

提交回复
热议问题