[英]javascript function execution sequence
我对javascript函数序列有疑问,下面有两个代码,为什么这两个程序的结果不同? 我认为第一个程序的结果将等于第二个程序的结果。
function test1() {
for (var i = 1; i <= 1000000; i++) {
}
console.log("test1");
}
function test2() {
console.log("test2");
}
test1();
test2();
//test1
//test2
function test1() {
setTimeout(function() {
console.log("test1");
}, 1000);
}
function test2() {
console.log("test2");
}
test1();
test2();
//test2
//test1
因为setTimeout
( MDN | spec )的目的是稍后异步地调度对函数的调用。 因此,在第二个示例中,您首先调用test1
,然后将调用调度到匿名回调中一秒钟,然后返回。 然后,您调用test2
立即打印。 一秒钟后,计时器将调用该回调,并输出test1
。
也许对您的第二个示例进行的细微调整将使其更加清晰:
function test1() { console.log("test1 called, setting up timer"); setTimeout(function() { console.log("timer fired and called the callback"); }, 1000); } function test2() { console.log("test2 called"); } test1(); test2();
您将看到以下输出(最后一行仅在一秒钟后出现):
test1 called, setting up timer test2 called timer fired and called the callback
setTimeout是一个异步操作,该数字用于定义代码执行的延迟。 1000
是延迟,因此您看到的结果有所不同
http://javascript.info/tutorial/settimeout-setinterval检查此内容可能会有所帮助:)
我认为,您当前的线程可能卡在了您的第一个代码段的“ for”循环中。 但是该操作是在第二个代码段中异步完成的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.