Skip to content

medelbou/js-multithreading

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Concurrency Model and Multithreading in Javascript

Start Server

npx http-server .

The Event Loop

The JavaScript engine runs an infinite loop, called the event loop, looking for tasks to run.

const queue = {
  waitForMessage: () => {
  },
  processNextMessage: () => {
  },
};

while (queue.waitForMessage()) {
  queue.processNextMessage()
}

The following code:

function funcOne() {
  funcTwo();
}

function funcTwo() {
  setTimeout(funcThree);
}

function funcThree() {
  console.log('Hello, World!');
}

funcOne();

Will result in this state:

Event Loop

Micro and Macro tasks

What will be the result of this code?

setTimeout(() => console.log('Message 1: setTimeout'));

Promise.resolve('Message 2: Promise').then(console.log);

console.log('Message 3: Sync code');

setTimeout and the promise callbacks are added to two different queues.

The promise callback is added to the micro task queue, which takes precedent over regular tasks.

the result will look like this:

Message 3: Sync code
Message 2: Promise
Message 1: setTimeout

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published