Javascript setInterval - 速率还是延迟? [英] Javascript setInterval - rate or delay?

查看:40
本文介绍了Javascript setInterval - 速率还是延迟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Javascript setInterval 方法是等待(至少)特定代码两次执行之间的指定间隔,还是等待上一次执行和下一次执行开始之间的间隔?

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?

(或者,与 Java 的 ScheduledExecutorService 方法相比 - setInterval 类似于 scheduleAtFixedRate() 还是 scheduleWithFixedDelay()?)

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

推荐答案

如果你以 1000 毫秒间隔调用 setInterval 并且回调代码需要 100> 运行毫秒,下一个回调将在 900 毫秒后执行.

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

如果回调需要1050毫秒,下一个将在第一个完成后立即触发(50毫秒延迟).这种延迟会不断累积.

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.

因此在 Java 世界中,这类似于 scheduleAtFixedRate().如果您需要 scheduleWithFixedDelay() 行为,您必须使用 setTimeout() 并重新安排回调每个完成时间:

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);

上面的代码将在 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.

这篇关于Javascript setInterval - 速率还是延迟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆