Asynchronous JavaScript in LWC · Lesson 13 of 25
The Event Loop and LWC Rendering
JavaScript runs your code on a single thread: one thing at a time. Yet a component can wait for Apex, run a timer and respond to clicks "at the same time". The event loop is how. Understanding it explains a whole family of LWC puzzles, like "I set the field, but querySelector still finds the old content".
In this lesson
- Synchronous vs asynchronous code
- Callbacks, the task queue and the microtask queue
- Predicting the order of output
- Why LWC re-renders after your code finishes
One thread, many waiting jobs
How the event loop runs your code
- Call stackruns the current synchronous code to the end – nothing interrupts it
- Microtasksthen every queued promise callback (then, await continuations)
- Renderingthe browser may update the screen
- Next taskone timer callback, click or network event – then back to step 1
Long-running work like an Apex call or a timer doesn't block the thread. You start it, hand over a callback, and the browser puts that callback in a queue when the result is ready.
console.log('1. handler starts');
setTimeout(() => console.log('5. timer callback (task)'), 0);
Promise.resolve().then(() => console.log('3. promise callback (microtask)'));
queueMicrotask(() => console.log('4. another microtask'));
console.log('2. handler ends');
1. handler starts 2. handler ends 3. promise callback (microtask) 4. another microtask 5. timer callback (task)
Even with a delay of 0, the timer runs last: setTimeout schedules a task, and all microtasks (promise callbacks) run before the next task. The synchronous code always finishes first.
Callbacks: the original async pattern
Before promises, async APIs took a callback to call later. You still meet them in setTimeout, addEventListener and older libraries. Their problem is nesting – each step depends on the previous one, so the code drifts right and error handling repeats:
function loadAccount(id, callback) {
setTimeout(() => callback(null, { Id: id, Name: 'Acme' }), 10);
}
function loadContacts(accountId, callback) {
setTimeout(() => callback(null, ['Ravi', 'Neha']), 10);
}
loadAccount('001A', (err, account) => {
if (err) return console.log('failed', err);
loadContacts(account.Id, (err2, contacts) => {
if (err2) return console.log('failed', err2);
console.log(`${account.Name}: ${contacts.join(', ')}`); // "callback pyramid" grows with every step
});
});
Acme: Ravi, Neha
Promises and async/await (the next two lessons) solve exactly this. Imperative Apex calls in LWC already return promises, so you'll rarely write callback-style code yourself.
Predict the output
Read this code and write down the order you expect before looking at the result:
async function save() {
console.log('save starts');
await null; // everything after await runs as a microtask
console.log('save resumes');
}
console.log('click');
setTimeout(() => console.log('timeout'), 0);
save();
Promise.resolve().then(() => console.log('then'));
console.log('click handler done');
click save starts click handler done save resumes then timeout
The rule that explains it: synchronous code first (click, save starts, click handler done – an async function runs synchronously until its first await), then microtasks in the order they were queued (save resumes was queued before then), then tasks (timeout).
Why the DOM isn't updated yet
LWC doesn't re-render the moment you assign a field. It schedules the render as a microtask, so ten field changes in one handler cause one render, not ten. The flip side: right after the assignment, the DOM still shows the old value.
// renderTiming.js
import { LightningElement } from 'lwc';
export default class RenderTiming extends LightningElement {
message = 'Old text';
async handleClick() {
this.message = 'New text';
const p = this.template.querySelector('p');
console.log(`right after assigning: ${p.textContent}`);
await Promise.resolve(); // let LWC's render microtask run
console.log(`after a microtask: ${p.textContent}`);
}
}
<!-- renderTiming.html -->
<template>
<p>{message}</p>
<lightning-button label="Change" onclick={handleClick}></lightning-button>
</template>
Old text [Change] › click “Change” New text [Change] console: right after assigning: Old text console: after a microtask: New text
Reading the DOM after a change
Prefer renderedCallback for work that depends on the rendered DOM (focusing an input that just appeared, measuring an element). await Promise.resolve() works in a handler, but it relies on timing details – and a setTimeout "to wait for render" is the fragile pattern LWC's lint rules warn about.
Practice
Try it yourself
What order do these print in?
setTimeout(() => log('x')); Promise.resolve().then(() => log('y')); log('z');Show answer
z, y, x – synchronous code, then the microtask, then the timer task.
After setting
this.showDetails = trueyou callthis.template.querySelector('lightning-input').focus()and get "Cannot read properties of null". Why, and where should the focus call go?Show answer
The input inside
lwc:ifisn't rendered yet – rendering happens in a later microtask. Focus it inrenderedCallback(guarded by a flag so it runs once), or afterawait Promise.resolve().
Quick check
Which runs first: a promise callback or a setTimeout(…, 0) callback?
The promise callback – microtasks run before the next task.
Can async code interrupt a running function?
No. Callbacks wait until the call stack is empty.
When does LWC update the DOM after a field change?
In a microtask after the current code finishes, batching all changes.
Summary
- JavaScript is single-threaded; async work finishes through queued callbacks.
- Order: synchronous code, then all microtasks, then the next task.
- Callbacks nest badly – promises and async/await replace them.
- LWC renders in a microtask, so the DOM updates after your code.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.