Javascript:带有 setInterval 的后台任务的理想块大小?
考虑一个通过 setTimeout
/ setInterval
定期执行后台任务的应用程序。一个函数调用应该完成的理想工作量是多少?
示例:
myTask = function() {
for (var i=0; i<chunkSize; i++) { ...work... }
}
setInterval(myTask, period);
如果您增加 chunkSize
(并且每次调用执行更多迭代),当然它会运行更长时间。这意味着,period
也必须增加,并且您可以减少调用该函数的频率。但我发现,尽管如此,块越大,完成的工作就越多。这可能是由于 setTimeout
/ setInterval
的开销造成的。
权衡是:较大的块大小使应用程序的反应性降低。这不仅涉及用户交互,还涉及其他间隔。因为只要函数正在运行其迭代,就不会触发其他间隔。因此,大块大小会使其他间隔不太准确,或者(在最坏的情况下)在某些浏览器中完全禁用它们,这样它们就不会再被调用。
如果您想
- 最大限度地完成工作量,
- 最大限度地减少对其他时间间隔的不良影响并保持准确,
实现这一目标的最佳方法是什么?如何确定合适的 chunkSize?或者我应该监视循环中的执行时间并在一定时间后中止?或者其他什么?
(顺便说一句,这是关于普通的旧 JavaScript,而不是 HTML5 WebWorkers)
Consider an application which periodically executes a background task via setTimeout
/ setInterval
. What's the ideal amount of work one function call should do?
Example:
myTask = function() {
for (var i=0; i<chunkSize; i++) { ...work... }
}
setInterval(myTask, period);
If you increase chunkSize
(and do more iterations per call), of course it will run longer. That means, the period
will also have to increase and you can call the function less often. But I found that nevertheless, the bigger the chunks, the more work gets done. This is probably due to overhead of setTimeout
/ setInterval
The trade-off is: bigger chunk sizes make the application less reactive. This does not only concern user interaction, but also other intervals. Because as long as the function is running its iterations, no other interval can get triggered. Thus, big chunk sizes make other intervals less accurate, or (in the worst case) completely disable them in some browsers so they don't get called anymore.
If you want to
- maximize the amount of work getting done
- minimize bad influence on other intervals and keep them accurate
what is the best way to achieve that? How do you determine a good chunkSize? Or should I monitor execution times in the loop and abort after a certain time? Or something else?
(btw, this is about plain old JavaScript, not HTML5 WebWorkers)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果可以的话,您应该使用
setTimeout
而不是setInterval
。无论上一个间隔的函数是否完成,setInterval
都会在period
之后调用该函数。使用setTimeout
,您可以确保函数在再次调用之前完成。If you can, you should use
setTimeout
instead ofsetInterval
.setInterval
will call the function afterperiod
whether the function from the previous interval is complete or not. WithsetTimeout
, you can make sure the function is complete before it called again.