Javascript setInterval - rate or delay?

感情迁移 提交于 2020-03-18 13:52:00

问题


Does the Javascript setInterval method wait (at least) the specified interval between two executions of the specific code, or does it wait that interval in between finishing the previous execution and the beginning of the next execution?

(or, when comparing to Java's ScheduledExecutorService methods - is setInterval similar to scheduleAtFixedRate() or rather scheduleWithFixedDelay()?)


回答1:


If you call setInterval with 1000 milliseconds interval and callback code takes 100 milliseconds to run, next callback will be executed after 900 milliseconds.

If callback takes 1050 milliseconds, the next one will fire up immediately after the first one finishes (with 50 milliseconds delay). This delay will keep accumulating.

So in Java world this is similar to scheduleAtFixedRate(). If you need scheduleWithFixedDelay() behaviour, you must use setTimeout() and reschedule callback each time it finishes:

function callback() {
    //long running code
    setTimeout(callback, 1000);
}
setTimeout(callback, 1000);

The code above will wait exactly 1000 milliseconds after callback() finished before starting it again, no matter how long it took to run.




回答2:


This answer includes help from jfriend00's comment below.

Javascript is single threaded and so the same function can not run twice at the same time. However the setInterval delay does not take into account how long it takes to run the function.

For example, say your setInterval function takes 500 milliseconds to run, and your delay is 1000 milliseconds. This would lead to a 500 millisecond delay before the function starts again.




回答3:


As you can see in this jsFiddle test case, setInterval tries to keep the interval on time regardless of how long the code that runs on the interval takes as long as that code takes less time than the interval is set for. So, if you have an interval set for 5 seconds and the code that runs on each interval takes 200ms, each interval should still be 5 seconds apart (or as close as a single threaded javascript engine can make it to 5 seconds).

If, on the other hand, the code you run on each interval takes long than the interval time itself to execute, because javascript is single threaded, the following interval will not start on time and will be delayed because of the time overrun of the first interval's code.

Both of these cases can be seen in this working test case by adjusting the delay time.

Working test case here: http://jsfiddle.net/jfriend00/kGQsQ/



来源:https://stackoverflow.com/questions/11408393/javascript-setinterval-rate-or-delay

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!