Microtask And Macrotask in JavaScript (Finally Explained Simply)
JavaScript looks simple, but sometimes its working becomes difficult to understand.
You write some code, and the you see a output in an order you didn’t expect. This confuses many beginners and even experienced developers.
The reason behind this is how JavaScript handles tasks in the background.
JavaScript does not run everything at the same time. It decides what to run now and what to run later.
This is where Microtasks and Macrotasks come in.
What Microtasks and Macrotasks are?
A Macrotask is a big task that JavaScript runs one by one.
Example of microtask are setTimeout,setInterval,UI events,setImmediate
What is a Microtask?
A Microtask is a small but very important task.
Example of microtask are Promise.then,
Promise.catch,Promise.finally and queue Microtask
Important:All microtasks run before any macrotask
Set timeout --> goes to macrotask queue
Promise.then--> goes to microtask queue
End --> runs immediately
JavaScript finishes normal code
JavaScript runs all microtasks
JavaScript runs one macrotask
Summary:In JavaScript, microtasks are executed first. Then macrotasks are executed after all microtasks are completed. This helps JavaScript work smoothly.




Comments
Post a Comment