Image
Image 企業ホームページのリニューアルを行いました。SEO対策を強化し、顧客獲得率を向上させました。

企業ホームページのリニューアルを行いました。SEO対策を強化し、顧客獲得率を向上させました。

Admin

By Admin

2025-02-09


In JavaScript, everything operates on a single thread, which makes handling asynchronous tasks like function calls and API requests a significant challenge. The event loop is a crucial mechanism that coordinates all activities and ensures that your JavaScript application remains smooth and uninterrupted. So, what is the Event Loop? ### JavaScript is a single-threaded language. JavaScript is a single-threaded language, meaning it executes one task at a time. → This presents a major limitation when you need to handle asynchronous tasks such as API calls, manipulating the DOM, handling events, and so on. ### What is Event Loop? The event loop is a mechanism that helps manage the execution of asynchronous tasks (such as callbacks, promises, async/await), ensuring they are processed in the correct order. - **Call Stack:** JavaScript uses the call stack to keep track of the functions that are currently being executed. It operates on a FILO (First In Last Out) principle. - **Callback Queue:** Asynchronous operations, such as I/O operations or timers, are handled by the browser or Node.js runtime. When these operations are completed, the corresponding functions (callbacks) are placed into the callback queue. - **Microtask Queue:** The queue with higher priority than the task queue. This queue is for: - Callbacks for handling Promises (then(callback), catch(callback), and finally(callback)) - Executing async functions after the `await` keyword - Callbacks for MutationObserver - Callbacks for `queueMicrotask` ### The process of the Event Loop The event loop works by continuously checking if the call stack is empty. If it is, it takes a task from the task queue and pushes it onto the call stack for execution. This ensures that tasks are executed in the designated order without interrupting the main operation of the application.

### Example

```bash console.log("Start"); setTimeout(() => { console.log("Inside setTimeout"); }, 2000); console.log("End"); ``` 

When running, "Start" will be printed first. Then, "End" will be printed immediately. After 2 seconds, "Inside setTimeout" will be printed. **Event Loop** ensures that although there is a delay (2 seconds), JavaScript continues to execute the following code without being blocked by the `setTimeout` function. ### Conclusion Understanding the Event Loop, Task Queue, and Microtask Queue The Event Loop coordinates the execution of tasks, prioritizing the Microtask Queue to ensure that promises and related operations are resolved quickly before moving on to tasks in the Task Queue.

Refs: https://www.lydiahallie.com/blog/event-loop%20https://www.geeksforgeeks.org/what-is-an-event-loop-in-javascript/%20https://youtu.be/eiC58R16hb8?si=Fqt3r6jrLpziEGRJ