Loop timer in JavaScript

前端 未结 6 938

I need to execute a piece of JavaScript code say, each 2000 milliseconds.

setTimeout(\'moveItem()\',2000)

The above will execute a function

6条回答
  •  星月不相逢
    2020-11-28 21:47

    Note that setTimeout and setInterval are very different functions:

    • setTimeout will execute the code once, after the timeout.
    • setInterval will execute the code forever, in intervals of the provided timeout.

    Both functions return a timer ID which you can use to abort the timeout. All you have to do is store that value in a variable and use it as argument to clearTimeout(tid) or clearInterval(tid) respectively.

    So, depending on what you want to do, you have two valid choices:

    // set timeout
    var tid = setTimeout(mycode, 2000);
    function mycode() {
      // do some stuff...
      tid = setTimeout(mycode, 2000); // repeat myself
    }
    function abortTimer() { // to be called when you want to stop the timer
      clearTimeout(tid);
    }
    

    or

    // set interval
    var tid = setInterval(mycode, 2000);
    function mycode() {
      // do some stuff...
      // no need to recall the function (it's an interval, it'll loop forever)
    }
    function abortTimer() { // to be called when you want to stop the timer
      clearInterval(tid);
    }
    

    Both are very common ways of achieving the same.

提交回复
热议问题