MyFunction()vs window.setTimeout('MyFunction()',0)? [英] MyFunction() vs window.setTimeout('MyFunction()', 0)?

查看:117
本文介绍了MyFunction()vs window.setTimeout('MyFunction()',0)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在javascript中,这两者之间有什么不同:

In javascript, is there any different between these two:

// call MyFunction normal way 

MyFunction();

// call MyFunction with setTimeout to 0 //

window.setTimeout('MyFunction()', 0);

我问的原因是因为最近遇到的情况是代码只有在我使用<$时才有效c $ c> setTimeout(0)调用该函数。
根据我的理解, setTimeout(0)与直接调用函数完全相同,因为你没有设置任何延迟。但从我看到它在代码中的工作方式来看, setTimeout(0)似乎最后执行。

The reason I asked was because recently came across the situation where the code only works if I use setTimeout(0) to call the function. To my understanding, setTimeout(0) is exactly same as calling a function directly because you dont set any delay. But from what I see how it works in the code, setTimeout(0) seems to get executed last.

有人能够确切地说明 setTimeout(0)是如何按照其他函数调用的顺序调用的?

Can someone clarify exactly how setTimeout(0) really get called in order of the rest of other function call?

推荐答案

setTimeout()始终导致阻止要排队等待执行的JavaScript。这是一个何时执行的问题,由延迟决定。
调用setTimeout(),延迟为0,将导致JavaScript解释器意识到它当前正忙(执行当前函数),并且解释器将调度脚本块在当前调用堆栈执行后执行空(除非有其他脚本块也排队)。

setTimeout() always causes the block of JavaScript to be queued for execution. It is a matter of when it will be executed, which is decided by the delay provided. Calling setTimeout() with a delay of 0, will result in the JavaScript interpreter realizing that it is currently busy (executing the current function), and the interpreter will schedule the script block to be executed once the current call stack is empty (unless there are other script blocks that are also queued up).

调用堆栈可能需要很长时间才能变为空,这就是你看到的原因延迟执行。这主要是由于单个窗口上下文中JavaScript的单线程特性。

It could take a long time for the call stack to become empty, which is why you are seeing a delay in execution. This is primarily due to the single-threaded nature of JavaScript in a single window context.

为了完整起见,MyFunction()将立即执行该函数。不会有排队。

For the sake of completeness, MyFunction() will immediately execute the function. There will be no queuing involved.

PS John Resig对JavaScript计时机制的工作原理有一些有用的说明

PPS :只有当你使用setTimeout(fn(),0)时你的代码似乎工作的原因是因为浏览器只有在当前调用堆栈完成时才能更新DOM。因此,下一个JavaScript块将识别DOM更改,这在您的情况下是非常可能的。 setTimeout()回调总是会创建一个新的调用堆栈。

PPS: The reason why your code "seems to work" only when you use setTimeout(fn(),0), is because browsers could update the DOM only when the current call stack is complete. Therefore, the next JavaScript block would recognize the DOM changes, which is quite possible in your case. A setTimeout() callback always creates a new call stack.

这篇关于MyFunction()vs window.setTimeout('MyFunction()',0)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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