Calling a function every 60 seconds

后端 未结 13 2083
情书的邮戳
情书的邮戳 2020-11-22 08:24

Using setTimeout() it is possible to launch a function at a specified time:

setTimeout(function, 60000);

But what if I would l

13条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 09:02

    If you don't care if the code within the timer may take longer than your interval, use setInterval():

    setInterval(function, delay)
    

    That fires the function passed in as first parameter over and over.

    A better approach is, to use setTimeout along with a self-executing anonymous function:

    (function(){
        // do some stuff
        setTimeout(arguments.callee, 60000);
    })();
    

    that guarantees, that the next call is not made before your code was executed. I used arguments.callee in this example as function reference. It's a better way to give the function a name and call that within setTimeout because arguments.callee is deprecated in ecmascript 5.

提交回复
热议问题