[Javascript] Task queue & Event loop.

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

posted @   Zhentiw  阅读(901)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示