JavaScript is a single-threaded, non-blocking asynchronous language, which means that code is executed in a sequential manner. The event loop is a mechanism that allows JavaScript to efficiently handle asynchronous operations. When an asynchronous task is encountered, it is placed in the event queue and executed when the current call stack is empty.
There are two types of tasks in the event loop: macro tasks and micro tasks. Macro tasks are tasks that are added to the end of the event queue and have higher priority than micro tasks. Examples of macro tasks include setTimeout, setInterval, and I/O operations. Micro tasks, on the other hand, have higher priority and are executed before macro tasks. Examples of micro tasks include Promise callbacks, MutationObserver callbacks, and process.nextTick.
Let's take a look at an example to better understand the event loop and tasks in JavaScript:
console.log('Script start');
setTimeout(() => {
console.log('setTimeout');
}, 0);
Promise.resolve().then(() => {
console.log('Promise');
});
console.log('Script end');
In this example, the output will be:
Script start
Script end
Promise
setTimeout
This is because the micro task (Promise callback) is executed before the macro task (setTimeout callback). Understanding the event loop and the concept of macro and micro tasks is crucial for writing efficient and scalable JavaScript code.
14/09/2024 | VanillaJS
22/10/2024 | VanillaJS
15/10/2024 | VanillaJS
14/09/2024 | VanillaJS
22/10/2024 | VanillaJS
21/07/2024 | VanillaJS
14/09/2024 | VanillaJS
22/10/2024 | VanillaJS
14/09/2024 | VanillaJS
25/07/2024 | VanillaJS