What are the microtask and macrotask within an event loop in JavaScript ?
Last Updated :
25 Jan, 2023
Event Loop: An Event Loop in JavaScript is said to be a constantly running process that keeps a tab on the call stack. Its main function is to check whether the call stack is empty or not. If the call stack turns out to be empty, the event loop proceeds to execute all the callbacks waiting in the task queue. Inside the task queue, the tasks are broadly classified into two categories, namely micro-tasks and macro-tasks.
Micro-tasks within an event loop: A micro-task is said to be a function that is executed after the function or program which created it exits and only if the JavaScript execution stack is empty, but before returning control to the event loop being used by the user agent to drive the script's execution environment. A Micro-task is also capable of en-queuing other micro-tasks.
Micro-tasks are often scheduled for things that are required to be completed immediately after the execution of the current script. On completion of one macro-task, the event loop moves on to the micro-task queue. The event loop does not move to the next task outside of the micro-task queue until all the tasks inside the micro-task queue are completed. This implies that the micro-task queue has a higher priority.
Once all the tasks inside the micro-task queue are finished, only then does the event loop shifts back to the macro-task queue. The primary reason for prioritizing the micro-task queue is to improve the user experience. The micro-task queue is processed after callbacks given that any other JavaScript is not under mid-execution. Micro-tasks include mutation observer callbacks as well as promise callbacks.
In such a case wherein new micro-tasks are being added to the queue, these additional micro-tasks are added at the end of the micro-queue and these are also processed. This is because the event loop will keep on calling micro-tasks until there are no more micro-tasks left in the queue, even if new tasks keep getting added. Another important reason for using micro-tasks is to ensure consistent ordering of tasks as well as simultaneously reducing the risk of delays caused by users.
Syntax: Adding micro-tasks:
queueMicrotask(() => {
// Code to be run inside the micro-task
});
The micro-task function itself takes no parameters and does not return a value.
Examples: process.nextTick, Promises, queueMicrotask, MutationObserver
Macro-tasks within an event loop: Macro-task represents some discrete and independent work. These are always the execution of the JavaScript code and the micro-task queue is empty. Macro-task queue is often considered the same as the task queue or the event queue. However, the macro-task queue works the same as the task queue. The only small difference between the two is that the task queue is used for synchronous statements whereas the macro-task queue is used for asynchronous statements.
In JavaScript, no code is allowed to execute until an event has occurred. {It is worth mentioning that the execution of a JavaScript code execution is itself a macro-task.} The event is queued as a macro-task. When a (macro) task, present in the macro-task queue is being executed, new events may be registered and in turn, created and added to the queue.
Up on initialization, the JavaScript engine first pulls off the first task in the macro-task queue and executes the callback handler. The JavaScript engine then sends these asynchronous functions to the API module, and the module pushes them to the macro-task queue at the right time. Once inside the macro-task queue, each macro-task is required to wait for the next round of the event loop. In this way, the code is executed.
All micro-tasks logged are processed in one fell swoop in a single macro-task execution cycle. In comparison, the macro-task queue has a lower priority. Macro tasks include parsing HTML, generating DOM, executing main thread JavaScript code, and other events such as page loading, input, network events, timer events, etc.
Examples: setTimeout, setInterval, setImmediate, requestAnimationFrame, I/O, UI Rendering
Similar Reads
Explain Promise.race() with async-await in JavaScript In this article, we will try to understand how we may implement Promise.race() method with async-await in JavaScript with the help of certain coding examples as well as theoretical explanations. Let us first quickly understand how we may implement Promise.race() method. This method is one of the mos
3 min read
How to delay a loop in JavaScript using async/await with Promise ? In JavaScript, you can delay a loop by using async/await with Promise. By wrapping a setTimeout() inside a Promise and using await, you can pause execution at each iteration, creating delays between loop iterations for asynchronous tasks without blocking the main thread.What is async and await?async
2 min read
What is An Event Loop in JavaScript? The event loop is an important concept in JavaScript that enables asynchronous programming by handling tasks efficiently. Since JavaScript is single-threaded, it uses the event loop to manage the execution of multiple tasks without blocking the main thread.JavaScriptconsole.log("Start"); setTimeout(
4 min read
How to use async/await with forEach loop in JavaScript ? Asynchronous is popular nowadays because it gives functionality of allowing multiple tasks to be executed at the same time (simultaneously) which helps to increase the productivity and efficiency of code. Async/await is used to write asynchronous code. In JavaScript, we use the looping technique to
2 min read
What is the Call Stack in JavaScript ? In JavaScript, the Call Stack is an essential concept that helps the JavaScript engine keep track of function execution. It plays a vital role in managing the execution order of functions and determining how the JavaScript program handles function calls.How Does the Call Stack Work?JavaScript operat
4 min read
Explain Promise.allSettled() with async-await in JavaScript In this article, we will try to understand how we may implement the Promise.allSettled() method with async-await in JavaScript with the help of certain coding examples as well as theoretical explanations. Let us first quickly understand about Promise.allSettled() method. This method is one of the mo
3 min read
What is Event Bubbling and Capturing in JavaScript ? Events are a fundamental construct of the modern web. They are a special set of objects that allow for signaling that something has occurred within a website. By defining Event listeners, developers can run specific code as the events happen. This allows for implementing complex control logic on a w
5 min read
What is the Event Driven Programming Paradigm ? Event-driven programming is a paradigm where the execution of a program is determined by events such as user actions or messages. Programs respond to events with predefined actions, allowing for asynchronous and responsive behavior, often seen in GUI applications and distributed systems. Advantages
3 min read
Explain Scope and Scope Chain in JavaScript In this article, we will try to understand what is the scope of a variable as well as its function (or method). We will see what is a Scope Chain with the help of certain coding examples. ScopeScope in JavaScript determines the accessibility of variables and functions at various parts of one's code
5 min read