[Javascript] Task queue & Event loop.

本文深入讲解了JavaScript在Chrome V8引擎中的执行原理,包括调用堆栈(call stack)的工作方式,以及异步操作如何通过Web APIs实现。文章还详细解释了事件循环(event loop)的作用,帮助读者理解setTimeout等异步函数的执行时机。

Javascript with Chorme v8 engine works like this :

For Chorme engine, v8, it has call stack. 

 

And all the async opreations functions are stay in webapis. So everytime  you call 'setTimeout()' or http call, it will always call webapis. 

 

So, in the picture, 

we call the main() function, and push into the call stack;

then console.log("Hi"); put into call stack and finish then poped up from the call stack;

third, setTimeout() function run into the call stack, then it call webapis with callback function, so push into webapis. And setTimeout() popup from the call stack.

fourth, console.log('JSC'); push into the call stack and poped up.

Finally main() finished and poped up:

So what left here is just webapis have a callback function, waiting 5 second, when the time out, it was push to the task queue, NOT to the call stack.

 

 

Now the 'Event loop' come in, what event loop does is: it check whether there is any task in the call stack.... if yes, finish those functions in the calll stack first. If not, then event loop checks the task queue then push the callback from the task queue to call stack.

 

Then console.log() function run and poped up from the call stack.

 

-----------------------------------------

 

You might have met the problem that you run setTimeout(fn(), 0); it wait no time, but the fn() come at last:

function one(){
  console.log("One");
}

function two(){
  console.log("Two");
}

function delay(){
  console.log("Delay");
}

one();
setTimeout(delay, 0);
two();

/*
"One"
"Two"
"Delay"
*/

 

That is because, setTimeout is webapis, so the callback function delay() will be pushed into the 'task queue'. It will wait all the functions in 'call stack' finish, then even loop will check the task queue and push the callback to the call stack. So the "Delay" console log out at the bottom.

Link: https://www.youtube.com/watch?v=8aGhZQkoFbQ

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值