How to set a timer in javascript

前端 未结 6 913
傲寒
傲寒 2020-12-03 06:21

I want to run the following code:

ajaxUpdate(10);

With a delay of 1 second between each iteration. How can I do this?

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-03 06:28

    var i = window.setInterval( function(){ 
              ajaxUpdate(10); 
     }, 1000 ); 
    

    This will call ajaxUpdate every second, until such a time it is stopped.

    And if you wish to stop it later:

    window.clearInterval( i ); 
    

    If you wish to only run it once however,

    var i = window.setTimeout( function(){ 
              ajaxUpdate(10); 
     }, 1000 ); 
    

    Will do the trick, and if you want to stop it running before it gets around to running once

    window.clearTimeout(i); 
    

    The "window" prefix is not strictly nessecary, but its a good idea, because you never know when somebody else might like to create something else with the same name in visible scope that behaves differently.

    For a complete reference on this, I always find MDC Very Helpful:

    • MDC: window.setInterval
    • MDC: window.clearInterval
    • MDC: window.setTimeout
    • MDC: window.clearTimeout

    Also, you may wish to read this article on timers by John Resig,

    • ejohn.org : How Javascript Timers work

提交回复
热议问题