Javascript 重复设置超时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11624078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:34:41  来源:igfitidea点击:

Repeating setTimeout

javascriptsettimeout

提问by Mr. 1.0

I am trying to repeat setTimeoutevery 10 seconds. I know that setTimeoutby default only waits and then performs an action one time. How can I repeat the process?

我试图setTimeout每 10 秒重复一次。我知道setTimeout默认情况下只等待然后执行一次操作。我怎样才能重复这个过程?

setTimeout(function() {
  setTimeout(function() {
    console.log("10 seconds");
  }, 10000);
}, 10000);

回答by uzyn

Maybe you should use setInterval()

也许你应该使用 setInterval()

回答by nnnnnn

setInterval()is probably what you're looking for, but if you want to do get the same effect with setTimeout():

setInterval()可能是您正在寻找的,但如果您想获得相同的效果setTimeout()

function doSomething() {
    console.log("10 seconds");
    setTimeout(doSomething, 10000);
}

setTimeout(doSomething, 10000);

Or if you don't want to declare a separate function and want to stick with a function expression you need to make it a namedfunction expression:

或者,如果您不想声明一个单独的函数并想坚持使用函数表达式,则需要将其设为命名函数表达式:

setTimeout(function doSomething() {
    console.log("10 seconds");
    setTimeout(doSomething, 10000);
}, 10000);

(Or use arguments.calleeif you don't mind using deprecated language features.)

(或者,如果您不介意使用已弃用的语言功能,请使用arguments.callee。)

回答by Rikin Thakkar

according to me setInterval() is the best way in your case.
here is some code :

根据我的说法, setInterval() 是您的最佳方法。
这是一些代码:

 setInterval(function() {

//your code

}, 10000); 
// you can change your delay by changing this value "10000".

回答by Aadit M Shah

Unlike the answers provided by @nnnnnn and @uzyn I discourage you from making use of setIntervalfor reasons elaborated in the following answer. Instead make use of the following Delta Timing script:

与@nnnnnn 和@uzyn 提供的答案不同setInterval,由于以下答案中详述的原因,我不鼓励您使用。而是使用以下 Delta Timing 脚本:

function DeltaTimer(render, interval) {
    var timeout;
    var lastTime;

    this.start = start;
    this.stop = stop;

    function start() {
        timeout = setTimeout(loop, 0);
        lastTime = + new Date;
        return lastTime;
    }

    function stop() {
        clearTimeout(timeout);
        return lastTime;
    }

    function loop() {
        var thisTime = + new Date;
        var deltaTime = thisTime - lastTime;
        var delay = Math.max(interval - deltaTime, 0);
        timeout = setTimeout(loop, delay);
        lastTime = thisTime + delay;
        render(thisTime);
    }
}

The above script runs the given renderfunction as close as possible to the specified interval, and to answer your question it makes use of setTimeoutto repeat a process. In your case you may do something as follows:

上面的脚本运行给定的render函数尽可能接近指定的interval,并回答你的问题,它利用setTimeout重复一个过程。在您的情况下,您可以执行以下操作:

var timer = new DeltaTimer(function (time) {
    console.log("10 seconds");
}, 10000);

var start = timer.start();

回答by RobG

Here is a function using setTimeout that tried to call itself as close as it can to a regular interval. If you watch the output, you can see the time drifting and being reset.

这是一个使用 setTimeout 的函数,它试图在尽可能接近固定间隔的情况下调用自己。如果你观察输出,你可以看到时间漂移和被重置。

<script type="text/javascript">

function Timer(fn, interval) {
  this.fn = fn;
  this.interval = interval;
}

Timer.prototype.run = function() {

    var timer = this;
    var timeDiff = this.interval;
    var now = new Date();  // Date.now is not supported by IE 8
    var newInterval;

    // Only run if all is good
    if (typeof timer.interval != 'undefined' && timer.fn) {

      // Don't do this on the first run
      if (timer.lastTime) {
        timeDiff = now - timer.lastTime;
      }
      timer.lastTime = now;

      // Adjust the interval
      newInterval = 2 * timer.interval - timeDiff;

      // Do it
      timer.fn();

      // Call function again, setting its this correctly
      timer.timeout = setTimeout(function(){timer.run()}, newInterval);
  }
}


var t = new Timer(function() {
  var d = new Date();
  document.getElementById('msg').innerHTML = d + ' : ' + d.getMilliseconds();
}, 1000);


window.onload = function() {
  t.run();
};
</script>

<span id="msg"></span>

回答by Shaze

Using jQuery, this is what you could do:

使用 jQuery,您可以这样做:

function updatePage() {

var interval = setTimeout(updatePage, 10000); // 10' Seconds

    $('a[href]').click(function() {
      $(this).data('clicked', true);
      clearInterval(interval); // Clears Upon Clicking any href Link
      console.log('Interval Cleared!');
    });
   // REPLACE 'YOUR_FUNCTION_NAME' function you would like to execute
    setTimeout(YOUR_FUNCTION_NAME, 500);

} // Function updatePage close syntax

updatePage(); // call the function again.