首页 技术 正文
技术 2022年11月15日
0 收藏 741 点赞 2,405 浏览 1536 个字

Javascript with Chorme v8 engine works like this :

[Javascript] Task queue & Event loop.

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.

[Javascript] Task queue & Event loop.

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:

[Javascript] Task queue & Event loop.

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.

[Javascript] Task queue & Event loop.

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.

[Javascript] Task queue & Event loop.

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

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,960
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,484
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,330
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,113
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,745
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,779