//
setTimeout(function(){
for(var i = 0; i < 100000000; iPP){}
console.log('timer a');
}, 0)
// 0,1,2,3,4
for(var j = 0; j < 5; jPP){
console.log(j);
}
//
setTimeout(function(){
console.log('timer b');
}, 0)
//
function waitFiveSeconds(){
console.log('finished waiting');
}
//
document.addEventListener('click', function(){
console.log('click');
})
// click begin
console.log('click begin');
// finished waiting
waitFiveSeconds();
//task
// for timer a
//
// timer b
1. All belong to Synchronize code
2. The code executes from top to bottom: execute console.log ('click begin') first; then waitFiveSeconds ();
, is it wrong?
console.log ('click begin'); and waitFiveSeconds (); are both Synchronize codes, which are executed sequentially.
setTimeout(function(){
for(var i = 0; i < 100000000; iPP){}
console.log('timer a');
}, 0)//00------4
for(var j = 0; j < 5; jPP){
console.log(j);//------1
}
setTimeout(function(){
console.log('timer b');
}, 0)//00------5
function waitFiveSeconds(){
console.log('finished waiting');//wait
}
document.addEventListener('click', function(){
console.log('click');//
})
console.log('click begin');//click begin------2
waitFiveSeconds();//waitfinished waiting------3
1. Put the timer in the queue
2. Execute the contents of the for loop and output 0 to 4
3. Execute console.log ("click begin");
4. Call the function waitFiveSeconds (), to execute console.log ("finished waiting")
5. Execute the timer in the queue
that's it. The js execution engine is single-threaded. All tasks are executed by Synchronize.
loads console.log ('click begin') from top to bottom, and then executes waitFiveSeconds ();.
other event timers are placed on threads other than another js engine to execute asynchronously
setTimeout(function(){
for(var i = 0; i < 100000000; iPP){}
console.log('timer a');
}, 0) //
for(var j = 0; j < 5; jPP){
console.log(j); // 1---04
}
setTimeout(function(){
console.log('timer b');
}, 0) //
function waitFiveSeconds(){
console.log('finished waiting');
}
document.addEventListener('click', function(){
console.log('click');
})
console.log('click begin'); // 2---click begin
waitFiveSeconds(); // 3---waitFiveSecondsfinished waitin
// 4---,timer a
// 5---,timer b
Brother, this is indeed caused by Synchronize asynchronous problems, JS single-threaded language, which determines its execution order from top to bottom. Based on this, Synchronize code will be executed at the time of parsing, while asynchronous code will be executed after Synchronize code execution is finished. You can understand that asynchronous code is temporarily placed in an asynchronous queue, and there is also an event loop problem. Synchronize asynchronism will lead to a lot of discussion, the journey is long, I will not stop pursuing.