博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Javascript] Task queue & Event loop.
阅读量:5163 次
发布时间:2019-06-13

本文共 1880 字,大约阅读时间需要 6 分钟。

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

转载于:https://www.cnblogs.com/Answer1215/p/5161622.html

你可能感兴趣的文章
解决Ubuntu下博通网卡驱动问题
查看>>
【bzoj2788】Festival
查看>>
执行gem install dryrun错误
查看>>
HTML5简单入门系列(四)
查看>>
实现字符串反转
查看>>
转载:《TypeScript 中文入门教程》 5、命名空间和模块
查看>>
苹果开发中常用英语单词
查看>>
[USACO 1.4.3]等差数列
查看>>
Shader Overview
查看>>
Reveal 配置与使用
查看>>
Java中反射的学习与理解(一)
查看>>
C语言初学 俩数相除问题
查看>>
B/S和C/S架构的区别
查看>>
[Java] Java record
查看>>
jQuery - 控制元素显示、隐藏、切换、滑动的方法
查看>>
postgresql学习文档
查看>>
Struts2返回JSON数据的具体应用范例
查看>>
js深度克隆对象、数组
查看>>
socket阻塞与非阻塞,同步与异步
查看>>
团队工作第二天
查看>>