简体   繁体   中英

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.

In the first example, I am using console.log() within my callback function. 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.

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. 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.

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. The speed of execution may be misleading as obviously the whole process is over in less than a second.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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