Microtask Queue in JavaScript | Promise vs setTimeout

Published: 25 May 2024
on channel: Mayank Srivastava
159
12

Here we have two console logs, first one inside the callback of a settimeout function with zero millisecond delay, the second one inside the dot then callback of a resolved promise, However when we execute this piece of code, we see that world gets logged before hello. But how can this be?even when the execution of the log statements has been deferred to run asynchronously and we registered the callback inside settimeout first and that too with a timer of 0 millisecond. This behavior can be explained by taking a closer look at the JavaScript 's event loop's mechanics and how the event loop divided events into microtasks and macrotasks and prioritizes one over the other. As we know Settimeout places the callback in the task queue, which will be processed in the next iteration of the event loop after the timer has been commpleted

When you resolve a promise, the .then() callbacks are scheduled as microtasks. These microtasks are processed immediately after the current synchronous code completes, but before any tasks from the task queue are executed. Microstask queue was introduced in the
ES6 revision of javascript in the year 2015. it was introduced to defer execution of functions but they should run as soon as possible, even before any rendering updates or other tasks.
While callbacks under settimeout setinterval are used to defer execution of a function but other pending tasks and rendering updates should happen first.


On this page of the site you can watch the video online Microtask Queue in JavaScript | Promise vs setTimeout with a duration of hours minute second in good quality, which was uploaded by the user Mayank Srivastava 25 May 2024, share the link with friends and acquaintances, this video has already been watched 159 times on youtube and it was liked by 12 viewers. Enjoy your viewing!