setInterval 和长时间运行的函数 [英] setInterval and long running functions

查看:57
本文介绍了setInterval 和长时间运行的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

setInterval 如何处理比所需时间间隔更长的回调函数?

我读到回调可能会接收延迟的毫秒数作为它的第一个参数,但我无法找到延迟的原因(抖动或长时间运行的函数).

还有精彩的跟进,它对常见浏览器的行为是否有所不同?

解决方案

让我引用一个优秀的 文章 由 John Resig 撰写的关于计时器的文章:

setTimeout(function(){/* 一些很长的代码块... */setTimeout(arguments.callee, 10);}, 10);设置间隔(函数(){/* 一些很长的代码块... */}, 10);

<块引用>

这两段代码可能看起来像首先在功能上是等效的一目了然,但他们不是.值得注意的是setTimeout 代码总是在在前一个之后至少有 10 毫秒的延迟回调执行(可能会结束多,但绝不会少)而setInterval 将尝试每 10ms 执行一次回调不管上次回调是什么时候被处决了.

如果间隔的执行时间足够长(长于指定的延迟),则它们可以无延迟地背靠背执行.

How does setInterval handle callback functions that take longer than the desired interval?

I've read that the callback may receive the number of milliseconds late as its first argument, but I was unable to find why it would be late (jitter, or long running functions).

And the wonderful follow up, does it behave differently for the common browsers?

解决方案

Let me quote an excellent article about timers by John Resig:

setTimeout(function(){
  /* Some long block of code... */
  setTimeout(arguments.callee, 10);
}, 10);

setInterval(function(){
  /* Some long block of code... */
}, 10);

These two pieces of code may appear to be functionally equivalent, at first glance, but they are not. Notably the setTimeout code will always have at least a 10ms delay after the previous callback execution (it may end up being more, but never less) whereas the setInterval will attempt to execute a callback every 10ms regardless of when the last callback was executed.

Intervals may execute back-to-back with no delay if they take long enough to execute (longer than the specified delay).

这篇关于setInterval 和长时间运行的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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