2016-08-02 164 views
-1

我有一个关于JavaScript函数序列的问题,下面我有两个代码,为什么这两个方案的不同的结果? 我认为第一个程序结果将等于第二个程序结果。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 
+0

运行的循环是同步,'setTimeout'是异步,这就是区别 – Thomas

回答

0

由于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 
0

setTimeout是一个异步操作,该数字用于定义代码将执行的延迟。 1000是延迟,所以您看到的结果不同

0

在我看来,也许你的当前线程陷在“for”循环在你的第一个代码片段。但是这个操作是在第二个代码片段中异步完成的。