This works because you're doing co-operative multi-tasking.
(之所以有效,是因为您正在执行协作式多任务处理。)
A browser has to do a number of things pretty much all at once, and just one of those is execute JavaScript.
(浏览器几乎必须一次完成许多事情,其中??之一就是执行JavaScript。)
But one of the things JavaScript is very often used for is to ask the browser to build a display element. (但是JavaScript经常使用的一件事是要求浏览器构建显示元素。)
This is often assumed to be done synchronously (particularly as JavaScript is not executed in parallel) but there is no guarantee this is the case and JavaScript does not have a well-defined mechanism for waiting. (通常认为这是同步完成的(特别是因为JavaScript不是并行执行的),但不能保证是这种情况,并且JavaScript没有明确的等待机制。)
The solution is to "pause" the JavaScript execution to let the rendering threads catch up.
(解决方案是“暂停” JavaScript执行,以使渲染线程赶上来。)
And this is the effect that setTimeout()
with a timeout of 0 does. (这就是setTimeout()
的超时值为0的效果。)
It is like a thread/process yield in C. Although it seems to say "run this immediately" it actually gives the browser a chance to finish doing some non-JavaScript things that have been waiting to finish before attending to this new piece of JavaScript. (就像C中的线程/进程产量一样。尽管似乎说“立即运行”,但实际上,它使浏览器有机会完成一些非JavaScript的事情,而这些事情在加入此新的JavaScript之前一直在等待完成。 。)
(In actuality, setTimeout()
re-queues the new JavaScript at the end of the execution queue. See the comments for links to a longer explanation.)
((实际上, setTimeout()
在执行队列的末尾重新排队新的JavaScript。有关更多说明的链接,请参见注释。))
IE6 just happens to be more prone to this error, but I have seen it occur on older versions of Mozilla and in Firefox.
(IE6恰好更容易出现此错误,但是我已经看到它发生在旧版本的Mozilla和Firefox中。)
See Philip Roberts talk "What the heck is the event loop?"
(参见Philip Roberts的演讲“事件循环到底是什么?”)
for more thorough explanation. (以获得更详尽的解释。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…