Concurrency model and the event loop in JavaScript

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.
The picture is from the website above

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值