Have you ever wondered why some pieces of JavaScript code seem to run out of order? The key to understanding this is the event loop.
JavaScript's event loop can be tricky to understand, especially when dealing with different types of asynchronous operations. In this article, we'll break down how JavaScript handles synchronous and asynchronous code, microtasks and macrotasks, and why certain things happen in a specific order.
JavaScript handles operations in two main ways: synchronous and asynchronous. Understanding the difference between them is key to grasping how JavaScript handles tasks and how to write efficient and non-blocking code.
Synchronous code is the default in JavaScript, meaning each line runs one after another in sequence. For example:
console.log("First"); console.log("Second");
This will output:
First Second
Asynchronous code on the other hand allows certain tasks to run in the background and complete later, without blocking the rest of the code. Functions like setTimeout() or Promise are examples of asynchronous code.
Here's a simple example of asynchronous code using setTimeout():
console.log("First"); setTimeout(() => { console.log("Second"); }, 0); console.log("Third");
This will output:
First Third Second
There are a few ways to handle asynchronous operations in JavaScript:
Code Sample:
console.log("Start"); function asyncTask(callback) { setTimeout(() => { console.log("Async task completed"); callback(); }, 2000); } asyncTask(() => { console.log("Task finished"); }); console.log("End");
Code Sample:
console.log("Start"); const asyncTask = new Promise((resolve) => { setTimeout(() => { console.log("Async task completed"); resolve(); }, 2000); }); asyncTask.then(() => { console.log("Task finished"); }); console.log("End");
Code Sample:
console.log("Start"); async function asyncTask() { await new Promise((resolve) => { setTimeout(() => { console.log("Async task completed"); resolve(); }, 2000); }); console.log("Task finished"); } asyncTask(); console.log("End");
To better understand each of these method of execution of javascript and how they differs from each either, here is an elaborate differences across multiple aspect of javascript functions.
Aspect | Synchronous Code | Asynchronous Code |
---|---|---|
Execution Order | Executes line by line in a sequential manner | Allows tasks to run in the background while other code continues to execute |
Performance | Can lead to performance issues if long-running tasks are involved | Better performance for I/O-bound operations; prevents UI freezing in browser environments |
Code Complexity | Generally simpler and easier to read | Can be more complex, especially with nested callbacks (callback hell) |
Memory Usage | May use more memory if waiting for long operations | Generally more memory-efficient for long-running tasks |
Scalability | Less scalable for applications with many concurrent operations | More scalable, especially for applications handling multiple simultaneous operations |
This comparison highlights the key differences between synchronous and asynchronous code, helping developers choose the appropriate approach based on their specific use case and performance requirements.
In JavaScript, microtasks and macrotasks are two types of tasks that are queued and executed in different parts of the event loop, which determines how JavaScript handles asynchronous operations.
Microtasks and macrotasks are both queued and executed in the event loop, but they have different priorities and execution contexts. Microtasks are processed continuously until the microtask queue is empty before moving on to the next task in the macrotask queue. Macrotasks, on the other hand, are executed after the microtask queue has been emptied and before the next event loop cycle starts.
Microtasks are tasks that need to be executed after the current operation completes but before the next event loop cycle starts. Microtasks get priority over macrotasks and are processed continuously until the microtask queue is empty before moving on to the next task in the macrotask queue.
console.log("Start"); Promise.resolve().then(() => { console.log("Microtask"); }); console.log("End");
Start End Microtask
Macrotasks are tasks that are executed after the microtask queue has been emptied and before the next event loop cycle starts. These tasks represent operations like I/O or rendering and are usually scheduled after a certain event or after a delay.
console.log("Start"); setTimeout(() => { console.log("Macrotask"); }, 0); console.log("End");
Start End Macrotask
Aspect | Microtasks | Macrotasks |
---|---|---|
Execution Timing | Executed immediately after the current script, before rendering | Executed in the next event loop iteration |
Queue Priority | Higher priority, processed before macrotasks | Lower priority, processed after all microtasks are complete |
Examples | Promises, queueMicrotask(), MutationObserver | setTimeout(), setInterval(), I/O operations, UI rendering |
Use Case | For tasks that need to be executed as soon as possible without yielding to the event loop | For tasks that can be deferred or don't require immediate execution |
The event loop is a fundamental concept in JavaScript that enables non-blocking asynchronous operations despite JavaScript being single-threaded. It's responsible for handling asynchronous callbacks and ensuring that JavaScript continues to run smoothly without getting blocked by time-consuming operations.
The event loop is a mechanism that allows JavaScript to handle asynchronous operations efficiently. It continuously checks the call stack and the task queue (or microtask queue) to determine which function should be executed next.
To understand the event loop better, it's important to know how JavaScript works internally. It is important to note that JavaScript is a single-threaded language, meaning it can only do one thing at a time. There's only one call stack, which stores the functions to be executed. This makes synchronous code straightforward, but it poses a problem for tasks like fetching data from a server or setting a timeout, which take time to complete. Without the event loop, JavaScript would be stuck waiting for these tasks, and nothing else would happen.
The call stack is where the function currently being executed is kept. JavaScript adds and removes functions from the call stack as it processes code.
When an asynchronous task like setTimeout, fetch, or Promise is encountered, JavaScript delegates that task to the browser's Web APIs (like Timer API, Network API, etc.), which handle the task in the background.
Once the asynchronous task completes (e.g., the timer finishes, or data is received from the server), the callback (the function to handle the result) is moved to the task queue (or microtask queue in the case of promises).
JavaScript continues executing the synchronous code. Once the call stack is empty, the event loop picks up the first task from the task queue (or microtask queue) and places it on the call stack for execution.
This process repeats. The event loop ensures that all the asynchronous tasks are handled after the current synchronous tasks are done.
Now that we a better and clearer understanding of how the event loop works, let's look at some examples to solidify our understanding.
function exampleOne() { console.log("Start"); setTimeout(() => { console.log("Timeout done"); }, 1000); Promise.resolve().then(() => { console.log("Resolved"); }); console.log("End"); } exampleOne();
Start End Resolved Timeout done
function exampleTwo() { console.log("Start"); setTimeout(() => { console.log("Timer 1"); }, 0); Promise.resolve().then(() => { console.log("Promise 1 Resolved"); setTimeout(() => { console.log("Timer 2"); }, 0); return Promise.resolve().then(() => { console.log("Promise 2 Resolved"); }); }); console.log("End"); } exampleTwo();
Start End Promise 1 Resolved Promise 2 Resolved Timer 1 Timer 2
function exampleThree() { console.log("Step 1: Synchronous"); setTimeout(() => { console.log("Step 2: Timeout 1"); }, 0); Promise.resolve().then(() => { console.log("Step 3: Promise 1 Resolved"); Promise.resolve().then(() => { console.log("Step 4: Promise 2 Resolved"); }); setTimeout(() => { console.log("Step 5: Timeout 2"); }, 0); }); setTimeout(() => { console.log( "Step 6: Immediate (using setTimeout with 0 delay as fallback)" ); }, 0); console.log("Step 7: Synchronous End"); } exampleThree();
Step 1: Synchronous Step 7: Synchronous End Step 3: Promise 1 Resolved Step 4: Promise 2 Resolved Step 2: Timeout 1 Step 6: Immediate (using setTimeout with 0 delay as fallback) Step 5: Timeout 2
In JavaScript, mastering synchronous and asynchronous operations, as well as understanding the event loop and how it handles tasks, is crucial for writing efficient and performant applications.
The examples provided progressively illustrated the interaction between synchronous code, promises, timers, and the event loop. Understanding these concepts is key to mastering asynchronous programming in JavaScript, ensuring your code runs efficiently and avoids common pitfalls such as race conditions or unexpected execution orders.
To ensure you don't miss any part of this series and to connect with me for more in-depth discussions on Software Development (Web, Server, Mobile or Scraping / Automation), push notifications, and other exciting tech topics, follow me on:
Stay tuned and happy coding ???
Clause de non-responsabilité: Toutes les ressources fournies proviennent en partie d'Internet. En cas de violation de vos droits d'auteur ou d'autres droits et intérêts, veuillez expliquer les raisons détaillées et fournir une preuve du droit d'auteur ou des droits et intérêts, puis l'envoyer à l'adresse e-mail : [email protected]. Nous nous en occuperons pour vous dans les plus brefs délais.
Copyright© 2022 湘ICP备2022001581号-3