Task Queue Priority and Order
You'll learn how tasks in JavaScript's event loop run in first-in-first-out order, but different task sources can have different priorities.
Understanding Task Order
Tasks (also called macrotasks) follow a FIFO (First In, First Out) rule within each task source. Think of it like a single-file line at a coffee shop: the first person to join the line gets served first, then the second, and so on.
setTimeout(() => console.log('First timeout'), 0);
setTimeout(() => console.log('Second timeout'), 0);
setTimeout(() => console.log('Third timeout'), 0);
// Output:
// First timeout
// Second timeout
// Third timeout
Each setTimeout creates a task in the order you called it, and they execute in that same order.
Task Source Priority
Here's where it gets interesting: different task sources may have different priorities. JavaScript has multiple task queues (timer tasks, I/O tasks, rendering tasks, etc.), and the browser can choose which queue to pull from next.
The specification doesn't mandate a strict priority order between different task sources—browsers have some flexibility. For example, a browser might prioritize user interaction tasks over timer tasks to keep the UI responsive.
setTimeout(() => console.log('Timer task'), 0);
// A click event might jump ahead depending on browser priority
button.onclick = () => console.log('User interaction task');
The key point: within one task source (like all your setTimeout calls), order is guaranteed FIFO. Between different task sources, priority may vary by browser implementation.
Key Takeaway: Tasks execute in FIFO order within their source, but the event loop may prioritize certain task sources (like user events) over others (like timers) between ticks.