问题描述
假设我有以下代码:
function testA {
setTimeout('testB()', 1000);
doLong();
}
function testB {
doSomething();
}
function doLong() {
//takes a few seconds to do something
}
我执行 testA()
。我已经读过Javascript是单线程的。 1000毫秒后,当达到 testB()
的超时时会发生什么?
I execute testA()
. I have read that Javascript is single-threaded. What happens after 1000 milliseconds, when the timeout for testB()
is reached?
我能想到的一些可能性:
Some possibilities I can think of:
-
testB()
在 doLong()以及它调用的任何其他内容已完成。 -
doLong()
立即终止并且testB()
已启动。 -
doLong()
获得一点点停止之前执行的时间更长(自动或在提示用户之后),并且testB()
已启动。 -
doLong()
暂停,testB()
已启动。在testB()
完成后,doLong()
恢复。
testB()
is queued up to execute afterdoLong()
and anything else it called have finished.doLong()
is immediately terminated andtestB()
is started.doLong()
is given a little while longer to execute before being stopped (either automatically or after prompting the user) andtestB()
is started.doLong()
is paused,testB()
is started. AftertestB()
has finished,doLong()
resumes.
答案是正确的?它是依赖于实现还是标准的一部分?*
What is the correct answer? Is it implementation dependant or part of the standard?*
类似但不一样,据我所知。
This question is similar but not the same, as far as I can tell.
为了更好地理解Javascript执行,你可以推荐任何链接我将不胜感激。
Any links that you can recommend for better understanding Javascript execution would be appreciated.
谢谢!
*是的,我知道并非所有浏览器都遵循标准:(
*Yes, I know that not all browsers follow standards :(
推荐答案
你猜测的第一个是正确的:
testB()排队在doLong()之后执行以及它调用的任何其他内容都已完成。
The first of your guesses is the correct one:testB() is queued up to execute after doLong() and anything else it called have finished.
如果需要超过一秒的时间> testA
完成, testB
只需等待。
此外,你应该写 setTimeout(testB,1000)
而不是 setTimeout('testB()',1000)
。发送一个字符串到setTimeout就像使用 eval
一样,通常被认为是邪恶的并会让你成为敌人;)
Also, you should write setTimeout(testB, 1000)
rather than setTimeout('testB()', 1000)
. Sending a string to setTimeout is, like using eval
, generally considered evil and will make you enemies ;)
这篇关于使用setTimeout()的Javascript执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!