[英]How JavaScript treats alert vs. console.log and their order of execution in callback functions
有人可以解釋以下代碼執行的工作方式嗎? 我已經創建了兩個涉及回調函數的場景,一個場景在回調中使用console.log,另一個場景使用Alert,並且我想知道是什么導致兩者之間的執行差異。
在第一個示例中,我在回調函數中使用console.log()。 見下文。
var thor = function(){
console.log('I am THOR!');
};
var otherFunction = function(callback){
for (var i = 0; i < 11; i++){
console.log(i);
}
callback();
};
otherFunction(thor);
結果如下:
0
1
2
3
4
5
6
7
8
9
10
"I am THOR!"
這是第二個例子。 唯一更改的是在“ thor”函數中將“ console.log”一詞替換為“ alert”。
var thor = function(){
alert('I am THOR!');
};
var otherFunction = function(callback){
for (var i = 0; i < 11; i++){
console.log(i);
}
callback();
};
otherFunction(thor);
...的結果是:
<alert>
0
1
9
10
8
7
6
5
4
3
2
for循環中的數字以隨機順序注銷,並且在登錄之前彈出警告框。 我想知道是什么原因導致這種差異,以及為什么在回調中調用警報時會先發生警報,而不是在for循環完成對數字的記錄之后發生警報。
謝謝您的幫助!
當我在chrome中進行測試時,警報會最后顯示,如果您將console.log添加到回調中,您會看到警報在數字之后發出。 執行速度可能會產生誤導,因為整個過程顯然不到一秒鍾就完成了。
小提琴: http : //jsfiddle.net/97vLmfrq/
var thor = function(){
console.log("in callback");
alert('I am THOR!');
};
var otherFunction = function(callback){
for (var i = 0; i < 11; i++){
console.log(i);
}
callback();
};
otherFunction(thor);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.