简体   繁体   English

JavaScript如何处理警报与console.log及其在回调函数中的执行顺序

[英]How JavaScript treats alert vs. console.log and their order of execution in callback functions

Could someone explain how the following execution of code works? 有人可以解释以下代码执行的工作方式吗? I have created two scenarios involving callback functions, one that uses console.log in the callback and another that uses alert, and I am wondering what causes the difference in execution between the two. 我已经创建了两个涉及回调函数的场景,一个场景在回调中使用console.log,另一个场景使用Alert,并且我想知道是什么导致两者之间的执行差异。

In the first example, I am using console.log() within my callback function. 在第一个示例中,我在回调函数中使用console.log()。 See below. 见下文。

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);

And here are the results: 结果如下:

0
1
2
3
4
5
6
7
8
9
10
"I am THOR!"

And here is the second example. 这是第二个例子。 The only thing that has changed are the words 'console.log' have been replaced with 'alert' in the 'thor' function. 唯一更改的是在“ 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);

...and the result is: ...的结果是:

<alert>
0
1
9
10
8
7
6
5
4
3
2

The numbers from the for loop are logged out in a random order, and the alert box pops up before they are logged. for循环中的数字以随机顺序注销,并且在登录之前弹出警告框。 I am wondering what causes this difference and why when alert is called in the callback that it occurs first instead of after the for loop has completed logging the numbers. 我想知道是什么原因导致这种差异,以及为什么在回调中调用警报时会先发生警报,​​而不是在for循环完成对数字的记录之后发生警报。

Thanks for the help! 谢谢您的帮助!

The alert comes last when I tested in chrome, if you add a console.log to the callback, you see it comes out after the numbers. 当我在chrome中进行测试时,警报会最后显示,如果您将console.log添加到回调中,您会看到警报在数字之后发出。 The speed of execution may be misleading as obviously the whole process is over in less than a second. 执行速度可能会产生误导,因为整个过程显然不到一秒钟就完成了。

fiddle: http://jsfiddle.net/97vLmfrq/ 小提琴: 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM