|
680 | 680 |
|
681 | 681 | In modern apps, Singletons are often implemented using **modules** or **closures**.
|
682 | 682 |
|
683 |
| - **[⬆ Back to Top](#table-of-contents)** |
| 683 | + **[⬆ Back to Top](#table-of-contents)** |
684 | 684 |
|
685 | 685 | 2. ### What is a prototype chain
|
686 | 686 |
|
|
7175 | 7175 | **[⬆ Back to Top](#table-of-contents)**
|
7176 | 7176 |
|
7177 | 7177 | 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: |
7178 | 7182 |
|
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. |
7181 | 7185 |
|
| 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 | + ``` |
7182 | 7222 | **Note:** All of these microtasks are processed in the same turn of the event loop.
|
7183 | 7223 |
|
7184 | 7224 | **[⬆ Back to Top](#table-of-contents)**
|
|
0 commit comments