Saved Bookmarks
| 1. |
Guess the outputs of the following codes: |
|
Answer» // Code 1: function func1(){ setTimeout(()=>{ console.log(x); console.log(y); },3000); var x = 2; let y = 12; } func1(); // Code 2: function func2(){ for(var i = 0; i < 3; i++){ setTimeout(()=> console.log(i),2000); } } func2(); // Code 3: (function(){ setTimeout(()=> console.log(1),2000); console.log(2); setTimeout(()=> console.log(3),0); console.log(4); })(); Answers:
4 3 1 // After two seconds Even though the second timeout function has a waiting time of zero seconds, the javascript engine always evaluates the setTimeout function using the Web API, and therefore, the complete function executes before the setTimeout function can execute. |
|