iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
The JavaScript event loop is the scheduler that lets an environment run JavaScript now and return to callbacks later. Your JavaScript engine executes one piece of synchronous code to completion. The browser or Node.js host supplies timers, network and file-system APIs, queues, and an event-loop mechanism that decides when deferred callbacks may run.
That model explains the ordering that confuses many developers: promise handlers usually run before a zero-delay timer, and setTimeout(..., 0) never means “run immediately.” The details differ between a browser and Node.js, so the useful mental model is simple but not universal.
What the event loop actually does
JavaScript does not pause a running function to let another callback cut in. A call stack records the functions currently executing. When the stack is empty, the host can take another runnable callback from its queues and start it. The event loop repeatedly coordinates that hand-off. MDN describes the execution model in terms of agents, execution contexts, jobs, and queues; each agent is driven by an event loop that is repeatedly processed (MDN JavaScript execution model).
Recommended Free Tools
The engine and the host have different jobs:
- Engine: parses and executes JavaScript, manages the call stack, and creates promise reactions.
- Host: implements APIs such as timers, DOM events, networking, file access, and rendering. It decides when those operations can enqueue callbacks.
- Event loop: selects queued work when the current JavaScript stack has finished.
In a browser window, page JavaScript and much of the user-interface work share a main-thread agent. A web worker has its own agent and event-loop context, so “the browser has one global JavaScript queue” is an oversimplification. The WHATWG HTML Standard defines the host-side event-loop algorithms (HTML Standard: Web application APIs).
#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
Run-to-completion: the rule everything else depends on
Suppose a click handler performs a long loop. A timer that becomes ready during that loop cannot interrupt the handler. The handler must return, its stack must unwind, and only then can another callback begin. This run-to-completion rule makes ordinary JavaScript code easier to reason about: while your function is running, another callback cannot mutate the same agent’s state halfway through an individual statement.
let count = 0;
setTimeout(() => {
console.log('timer sees', count);
}, 0);
for (let i = 0; i < 100000000; i++) {
count++;
}
console.log('loop finished');
The timer may become eligible while the loop is executing, but it cannot print until the loop and the surrounding script have completed. A large synchronous calculation therefore blocks input, timers, promise callbacks, and (in a typical window) rendering. “Asynchronous” means the host can arrange work for later; it does not make the currently executing JavaScript interruptible.
Tasks and microtasks: two kinds of deferred work
Browsers use task queues for larger callbacks and a microtask queue for short follow-up jobs. A browser event-loop turn is commonly taught as: run one task, drain microtasks, then possibly take a rendering opportunity before continuing. Rendering is a host decision, not a promise that a paint occurs after every task, and browsers can have multiple task sources.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
| Property | Task | Microtask |
|---|---|---|
| Typical examples | Initial script, user-event callback, timer callback, many network or message callbacks | Promise .then()/catch()/finally() reactions, queueMicrotask(), MutationObserver callbacks |
| When it runs | When the host selects that task and the current stack is empty | After the current JavaScript job finishes, before the browser proceeds to another task |
| Queue behavior | The host chooses among task sources according to its scheduling rules | Usually drained completely before the next task is selected |
| Main risk | Long callbacks delay everything behind them | A chain that keeps adding microtasks can delay tasks and rendering |
MDN’s microtask guide explains that promise reactions and queueMicrotask() callbacks are processed after the current stack, while timer callbacks are tasks (MDN: Using microtasks in JavaScript with queueMicrotask()). Microtasks are intended for brief consistency work, not for an unbounded computation.
Why a promise runs before setTimeout(..., 0)
Consider this browser teaching example:
console.log('A');
setTimeout(() => console.log('timer'), 0);
Promise.resolve().then(() => console.log('promise'));
console.log('B');
The expected order is:
ABpromisetimer
The initial script is the current task. It prints A, registers the timer, schedules a promise reaction, and prints B. When the script finishes, the stack is empty. The browser drains the microtask queue, so the promise reaction prints next. Only after that can the timer callback be selected as a later task. This is a standards-based browser illustration; it is not a claim that every asynchronous API shares one universal queue.
Microtasks can enqueue more microtasks. The host keeps draining them before moving on, which is why a self-perpetuating chain can starve timers, input, and painting. MDN documents this starvation risk in its detailed runtime guide (MDN: In depth—Microtasks and the JavaScript runtime environment).
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
Why zero-delay timers are not immediate
setTimeout(callback, 0) asks the host to make callback eligible after the timer’s minimum-delay rules. It does not reserve a precise execution time or jump ahead of code already running. The callback still waits for:
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchPC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11- the current synchronous script or callback to finish;
- microtasks that must be drained;
- other runnable work the host schedules ahead of it;
- available event-loop time and, in a browser, rendering and input scheduling decisions.
The HTML Standard specifies timer behavior and eligibility, not a guarantee that a callback executes exactly at the requested delay (WHATWG HTML Standard: Timers and user prompts). Use a zero-delay timer to yield to a later task, not as a stopwatch or synchronization primitive.
Where rendering fits in a browser
After a task and its microtasks finish, the browser may update styles, lay out elements, paint, and composite a frame. The opportunity depends on frame timing, pending work, visibility, and the browser’s scheduler. A microtask loop can therefore make a page appear frozen even when each individual microtask is tiny.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
For visual work, keep each callback short and split heavy computation into chunks that yield back to the host. A timer or a frame-oriented API can create a later task or rendering-aligned callback; the correct choice depends on whether you are waiting for a new task, a paint opportunity, or idle time. Do not assume that adding Promise.resolve().then(...) yields to rendering: it stays in the microtask checkpoint and may run before the browser paints.
Preventing microtask and callback starvation
Break unbounded microtask chains
This pattern can monopolize an agent:
function keepGoing() {
queueMicrotask(keepGoing);
}
keepGoing();
Because each microtask schedules another, the queue never becomes empty. A safer design processes a bounded batch, then yields through a task boundary before continuing. The batch size should reflect the work and responsiveness your application needs; there is no universal number that guarantees smoothness.
Chunk CPU-heavy synchronous work
Move independent units of work into bounded chunks and schedule the next chunk later. This lets input and rendering get opportunities between chunks. For truly parallel computation, use workers where appropriate; a worker has its own event-loop context, but communication still requires messages and serialization or transferable data.
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Keep callbacks short
Whether a callback came from a timer, a click, a promise, or a network response, it blocks subsequent work on its agent until it returns. Measure long tasks with browser developer tools and inspect the call stack rather than assuming the timer or promise itself is slow.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Browser and Node.js: related ideas, different loops
Node.js uses an event loop to provide non-blocking I/O while JavaScript execution is single-threaded by default. Its runtime delegates many operations to the operating system and its native libraries, then invokes JavaScript callbacks when results are ready. Node’s official guide describes a phase-based loop, so a browser diagram should not be copied directly into a Node program (Node.js: The Node.js Event Loop, Timers, and nextTick()).
| Aspect | Browser | Node.js |
|---|---|---|
| Host responsibilities | DOM events, timers, networking, messaging, and possible rendering | Timers, filesystem and network I/O, process events, and native runtime facilities |
| Scheduling shape | Tasks and microtask checkpoints associated with an agent; multiple task sources | Phases including timers, pending callbacks, poll, check, and close-callback processing |
| Rendering | May occur between turns when the browser schedules a rendering opportunity | No browser painting phase |
| Special APIs | queueMicrotask(), DOM events, frame and worker APIs |
process.nextTick(), setImmediate(), and Node-specific I/O APIs |
process.nextTick() and setImmediate()
process.nextTick() is a Node-specific queue that runs after the current operation and before the event loop proceeds normally. Repeatedly scheduling it can starve I/O for the same reason as an endless browser microtask chain. setImmediate() is associated with Node’s check phase. Their relative order can depend on where they are scheduled, especially inside or outside an I/O callback, so avoid rules that promise one universal ordering. Consult the current Node guide when code depends on phase details.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
A practical way to predict callback order
- Mark the current synchronous job. Everything in it runs in source order until the stack returns.
- Identify what each API schedules. Promise reactions and
queueMicrotask()are microtasks in browser JavaScript; timers enqueue later callbacks as tasks. Node-specific APIs follow Node’s own queues and phases. - Drain microtasks at the applicable checkpoint. Include microtasks created by earlier microtasks.
- Account for host work. Browser rendering, user input, task-source selection, operating-system I/O, and Node phases can affect when a callback becomes runnable.
- Check for blocking code. A long loop or callback delays every later callback on that agent.
When debugging, add a label at each scheduling boundary and record the order in which labels appear. Do not infer timing from the requested timer delay. In a browser, the Performance panel can reveal long tasks and rendering gaps; in Node, inspect event-loop delay and phase-sensitive behavior with the runtime’s current diagnostics.
Common misconceptions corrected
- “JavaScript is asynchronous.” JavaScript execution is synchronous by default. The host provides asynchronous APIs that arrange later callbacks.
- “The event loop runs callbacks in one giant queue.” Browsers distinguish tasks and microtasks and have multiple task sources; Node has its own queues and phases.
- “A promise is faster than a timer.” The important difference is queue category and ordering, not a guaranteed execution-speed advantage.
- “Zero milliseconds means immediate.” It means eligible after the timer rules and all work ahead of the callback.
- “Microtasks always improve responsiveness.” A short microtask can preserve ordering, but an endless chain delays tasks and visual updates.
- “All browser JavaScript shares one loop.” Workers run in separate agent contexts; communication between them is explicit.
Further reading
For current browser behavior, start with the MDN runtime guide, the MDN microtask guide, and the WHATWG HTML Standard. For server-side JavaScript, use Node’s event-loop documentation.
Kyle Simpson’s You Don’t Know JS: Async & Performance is a 296-page, intermediate-to-advanced book published in February 2015. Its chapters cover “Asynchrony: Now & Later,” the event loop, promises, generators, and Web Workers. Because it predates many current platform details, pair it with today’s MDN, WHATWG, and Node.js documentation. The publisher listing is available at O’Reilly Media.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.
Free tools Windows power users keep installed
One-click scans. No signup required.

