Concurrency model and the event loop
Note: this is a simple summary based on
https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#visual_representation. And the picture below is from the website.
Besides,I guess the blog is not suitable for beginners to learn. The blog is mostly like a record of my learning.
Stack
When a function is called, a corresponding frame is created and is pushed on the top of the stack. When the function returns, the frame is poped out of stack.
Note: the arguments and local variables may continue to exist, as they are stored outside the stack.
Heap
Objects are allocated here.
Queue
A list of messages stored here. Message starting to be handled - messages removed - fuction called - frames created in Stack - Stack empty - next message starting to be handled
Event loop
Run-to-completion
Each message is processed completely before any other message is processed.
It won’t be stopped by some other code in anther thread.
Adding messages
a click on an element with a click event handler will add a message.
setTimeout(message,delay time after the queue and stack are empty).
(function() {
console.log('this is the start');
setTimeout(function cb() {
console.log('Callback 1: this is a msg from call back');
}); // has a default time value of 0
console.log('this is just a message');
setTimeout(function cb1() {
console.log('Callback 2: this is a msg from call back');
}, 0);
console.log('this is the end');
})();
// "this is the start"
// "this is just a message"
// "this is the end" --a function(message) is completely handled and then a new function (message) starts
// "Callback 1: this is a msg from call back"
// "Callback 2: this is a msg from call back"
Never blocking
Thanks to events and callbacks and queue, JavaScript never blocks when handling I/O.
reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#visual_representation