What browser works?
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
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.
//Synchronous way
[1,2,3,4,5].forEach(function(i) {
console.log('processing sync');
delay();
});
//Asynchronous way
function asyncForEach(array, callback) {
array.forEach(function() {
setTimeout(callback, 0);
});
}
asyncForEach([1,2,3,4,5], function() {
console.log("processing async");
delay();
});
// more code are executed after that...
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?