Skip to content

Commit 2182bbe

Browse files
committed
Update microtask question
1 parent 144e761 commit 2182bbe

File tree

1 file changed

+43
-3
lines changed

1 file changed

+43
-3
lines changed

README.md

+43-3
Original file line numberDiff line numberDiff line change
@@ -680,7 +680,7 @@
680680

681681
In modern apps, Singletons are often implemented using **modules** or **closures**.
682682

683-
**[⬆ Back to Top](#table-of-contents)**
683+
**[⬆ Back to Top](#table-of-contents)**
684684

685685
2. ### What is a prototype chain
686686

@@ -7175,10 +7175,50 @@
71757175
**[⬆ Back to Top](#table-of-contents)**
71767176
71777177
388. ### What is microtask
7178+
7179+
A microtask is a type of JavaScript callback that is scheduled to run immediately after the currently executing script and before the next event loop tick. Microtasks are executed after the current task completes and before any new tasks (macrotasks) are run. This ensures a fast and predictable update cycle.
7180+
7181+
Common sources of microtasks stored in the microtask queue include:
71787182
7179-
Microtask is used for the javascript code which needs to be executed immediately after the currently executing task/microtask is completed. They are kind of blocking in nature. i.e, The main thread will be blocked until the microtask queue is empty.
7180-
The main sources of microtasks are Promise.resolve, Promise.reject, MutationObservers, IntersectionObservers etc
7183+
1. **Promises:**
7184+
When a Promise is resolved or rejected, its `.then()`, `.catch()`, and `.finally()` callbacks are placed in the microtask queue.
71817185
7186+
```javascript
7187+
Promise.resolve().then(() => {
7188+
console.log('Microtask from a Promise');
7189+
});
7190+
```
7191+
7192+
2. **queueMicrotask():**
7193+
7194+
A method that explicitly schedules a function to be run in the microtask queue.
7195+
7196+
```javascript
7197+
queueMicrotask(() => {
7198+
console.log('Microtask from queueMicrotask');
7199+
});
7200+
```
7201+
7202+
3. **MutationObserver callbacks:**
7203+
7204+
Observers changes in the DOM and triggers a callback as a microtask.
7205+
7206+
```javascript
7207+
const observer = new MutationObserver(() => {
7208+
console.log('Microtask from MutationObserver');
7209+
})
7210+
observer.observe(document.body, {childList: true});
7211+
```
7212+
7213+
4. **await:**
7214+
Await internally uses Promises, so the code after `await` is scheduled as a microtask.
7215+
7216+
```javascript
7217+
async function asyncFunction() {
7218+
await null;
7219+
console.log('Microtask from Await'); // Schedule this code as microtask
7220+
}
7221+
```
71827222
**Note:** All of these microtasks are processed in the same turn of the event loop.
71837223
71847224
**[⬆ Back to Top](#table-of-contents)**

0 commit comments

Comments
 (0)