Skip to content

Instantly share code, notes, and snippets.

@dominikkaegi
Last active February 12, 2019 14:57
Show Gist options
  • Select an option

  • Save dominikkaegi/0b696535d290786c85fec82067990f33 to your computer and use it in GitHub Desktop.

Select an option

Save dominikkaegi/0b696535d290786c85fec82067990f33 to your computer and use it in GitHub Desktop.
This gist showcases the prioritisation of the Microtask Queue over the Task Queue
/**
* Microtask Queue vs Task Queue
* Prioritisation between Microtask Queue (also named Job Queue) and Task Queue
*
* There are two queues for executing asynchronous javascript. The Micro Task queue has priority over the Task Queue.
* If you would keep on filling the micro task queue, you would block the code on the task queue.
* Asynchronous code which returns objects (like promises) are getting added to the Micro Task Queue.
* Asynchronous code which leave no trace (like setTimeout()) are getting added to the Task Queue.
*/
showcaseQueuePrioritisation()
function showcaseQueuePrioritisation() {
// Task Queue
setTimeout(() => console.log('task queue'), 1000)
blockFor3000ms()
// Micro Task / Job Queue
new Promise((resolve, reject) => {
resolve('microtask / job queue')
}).then(value => console.log(value))
blockFor3000ms()
}
function blockFor3000ms () {
// Block Event Loop for about 3000 ms
startTime = Date.now()
for(let i = 0; i < 3500000000; i++) {
}
endTime = Date.now()
diffTime = endTime - startTime
console.log('Event Loop Blocked for: ' + diffTime + ' ms')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment