[removed] get code to run every minute

前端 未结 2 1294
星月不相逢
星月不相逢 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);
    
    0 讨论(0)
  • 2020-11-28 06:59

    You could use setInterval for this.

    <script type="text/javascript">
    function myFunction () {
        console.log('Executed!');
    }
    
    var interval = setInterval(function () { myFunction(); }, 60000);
    </script>
    

    Disable the timer by setting clearInterval(interval).

    See this Fiddle: http://jsfiddle.net/p6NJt/2/

    0 讨论(0)
提交回复
热议问题