Loading...
「ツール」は右上に移動しました。
利用したサーバー: wtserver1
14いいね 312 views回再生

Microtask Queue in JavaScript | Promise vs setTimeout #javascript #coding #codinginterview #shorts

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.

コメント