0

I'm reading an article that explains the event loop and execution timings. In it, it's mention that there can be multiple task queues that the event loop can choose to from to execute tasks. My main question is when does the browser decide to create a new queue? I've tried to observe this happening, but so far haven't been able to.

Contrasted with this other article on the subject, there's no mention of multiple queues, so I'm either misunderstanding something or one of the two articles is incorrect somewhere.

Dan
  • 119
  • 7
  • The event-loop is not part of the JavaScript (ECMAScript) standard and is implementation-specific. I don't believe you can observe it via JavaScript. – Scott Marcus Jul 28 '17 at 16:38

2 Answers2

0

I believe the two articles in question are just using different terminology.

In article 1:

An event loop has multiple task sources which guarantees execution order within that source...

In article 2

the event loop can have multiple task queues... tasks must be processed in insertion order in every queue.

To answer my own question about observing different queues, I think it's as simple as this:

function foo() {
  console.log('Start of queue');
  bar();
  Promise.resolve().then(function() {
    console.log('Promise resolved');
  });
  console.log('End of queue');
}

function bar() {
  setTimeout(function() {
    console.log('Start of next queue');
    console.log('End of next queue');
  }, 0);
}

foo();
//-> Start of queue
//-> End of queue
//-> Promise resolved
//-> Start of next queue
//-> End of next queue

The first task queue (or task source) is foo(). foo() calls bar(), and bar() calls a setTimeout() which sets up a new task queue (or task source). The way we can observe each task queue is to resolve a Promise. The Promise callback is inserted into the micro queue. All micro queue tasks are executed at the end of every task queue (or task source). Because we see Promise resolved between the End of queue and Start of next queue console logs, we can conclude that that we're observing different event queues.

Dan
  • 119
  • 7
0

https://www.youtube.com/watch?v=u1kqx6AenYw&feature=youtu.be This will help you understand I think. Skip to the 7min mark.

There can be multiple queues in the task queue, and then also micro task queue.

In HTML terms, the event loop for a page or set of pages from the same domain can have multiple task queues. Tasks from the same task source always go into the same queue, with the browser choosing which task queue to use next.

user3919920
  • 355
  • 3
  • 8