JavaScript Internals (521 Qs)•Part 6: Async Internals, Memory, Microtasks & Web APIs (329 - 403)
What are tasks in event loop
A task is any javascript code/program which is scheduled to be run by the standard mechanisms such as initially starting to run a program, run an event callback, or an interval or timeout being fired. All these tasks are scheduled on a task queue. Below are the list of use cases to add tasks to the task queue,
- When a new javascript program is executed directly from console or running by the
<script>element, the task will be added to the task queue. - When an event fires, the event callback added to task queue
- When a setTimeout or setInterval is reached, the corresponding callback added to task queue
Practical Code Example
javascript
// Tasks (Macrotasks) in the Event Loop:
// Tasks include setTimeout, setInterval, I/O, UI rendering, and setImmediate (Node.js).
// Each turn of the event loop processes exactly ONE macrotask from the queue,
// then drains all pending microtasks before the next macrotask.