In JavaScript, tasks can be broadly categorized into two types: micro tasks and macro tasks. Micro tasks are tasks that are executed after the current task has finished executing, while macro tasks are tasks that are queued in the event loop to be executed in the future.
Micro tasks are tasks that are executed immediately after the current task has finished executing. Examples of micro tasks include promises, process.nextTick, and Object.observe. Micro tasks are executed before any other tasks, including macro tasks. This ensures that micro tasks are prioritized and executed as soon as possible.
console.log('Start'); Promise.resolve().then(() => console.log('Micro task')); console.log('End');
In the above example, the micro task will be executed before the 'End' log statement, even though it was defined after the 'End' statement.
Macro tasks, on the other hand, are tasks that are queued in the event loop to be executed in the future. Examples of macro tasks include setTimeout, setInterval, and requestAnimationFrame. Macro tasks are executed after all micro tasks have been executed. This means that macro tasks have a lower priority compared to micro tasks.
console.log('Start'); setTimeout(() => console.log('Macro task'), 0); console.log('End');
In this example, the 'Macro task' log statement will be executed after the 'End' log statement, even though it was defined before the 'End' statement.
The event loop is responsible for handling the execution of tasks in JavaScript. It keeps track of both micro tasks and macro tasks and ensures that they are executed in the appropriate order. The event loop continuously checks the task queue for any pending tasks and executes them accordingly.
Overall, understanding the difference between micro tasks and macro tasks in JavaScript is essential for writing efficient and optimized code. By prioritizing micro tasks over macro tasks, you can ensure that critical tasks are executed as soon as possible. Next time you work with asynchronous JavaScript code, keep in mind the distinction between micro tasks and macro tasks to improve the performance of your code.
15/10/2024 | VanillaJS
22/10/2024 | VanillaJS
14/09/2024 | VanillaJS
22/10/2024 | VanillaJS
12/09/2024 | VanillaJS
22/10/2024 | VanillaJS
22/10/2024 | VanillaJS
14/09/2024 | VanillaJS
14/09/2024 | VanillaJS
22/10/2024 | VanillaJS