Last active
February 12, 2019 14:57
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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