JavaScript and his little friends

Soanseng
·
·
IPFS
·

I recently learn the JavaScript. I am fascinated with beautiful world that the modern Internet give me. There are so many cool features and tools that JavaScript give us. Oh, wait here. Exactly, It is not the JavaScript only. But the web browser give us. If you review the history of JavaScript, you would understand that JavaScript are intertwined with the web browser. So, Only the JavaScript are not so cool stuff. But JavaScript works with modern web browser are cool. But Why do we have to understand which part provided by JavaScript? which part provided by WebAPIs ? Most of time, you don’t have to figure it out. You just work with them together. But if we want to go deep, and truly understand javascript, I think it is good to figure it out how both of them work together.

JavaScript in the Browser

How bowser work

We can view a browser as the combination of JavaScript engine, event loop, event queue, and WebAPIs. So, if you have already known that JavaScript is a single thread, single call stack.(execution one piece of code at a time). When I learn about setTimeout function in the JavaScript, I am confused. So here is the answer, setTimeout is provided by WebAPIs.

In MDN:Concurrency model and Event loop:

JavaScript has a concurrency model based on an “event loop”.

So if you put a piece of code to execute later, the event loop will take care for it. The JavaScript itself are not able to do it. It call for helps!

Event in Node.js, because of Chrome engine V8, it also provide those methods like setTimeout.

I want to play around it

Of course, you can play around with it! Here, the loupe give you a visualization to paly around it.

In the previous example, in you use the asynchronous way to deal with the dealy(). You can view from this example. All the callback are used by WebAPIs setTimeout, then stored in the Callback Queue. If I have more code that will be executed after the forEach. I don’t have to wait all the 1 to 5 to finish, execute the after code part first, and when the delay(in the setting of loupe, it is 750ms) are met, execute them. This is how async works in JavaScript with his little friend WebAPIs. This code example are from the video:

Philip Roberts: What the heck is the event loop anyway?

Published on March 16, 2017


Originally published at http://poligen.gitlab.io/javascript-and-his-little-friends/ on March 16, 2017.

CC BY-NC-ND 2.0 授权

喜欢我的作品吗?别忘了给予支持与赞赏,让我知道在创作的路上有你陪伴,一起延续这份热忱!