2016-08-02 117 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」循環在你的第一個代碼片段。但是這個操作是在第二個代碼片段中異步完成的。