The call stack and synchronous execution
function calculateTotal(price, quantity) {
return price * quantity;
}
function renderTotal() {
const total = calculateTotal(25, 3);
console.log(total);
}
renderTotal();
console.log("done");
// 75, done
A function call creates an execution context on the call stack. In the example, renderTotal calls calculateTotal; only after the calculation returns does it log 75, followed by done. Within a JavaScript agent, synchronous code runs to completion before the next independent unit of work can execute. [1][2]
The browser can handle networking and other operations outside the main thread, but a response callback does not interrupt an arbitrary JavaScript instruction. If main-thread computation takes 200 ms, click handling and DOM updates may have to wait. Adding async does not turn expensive computation into parallel work.
Tasks and microtasks: execution order
console.log("start");
setTimeout(() => {
console.log("timer");
}, 0);
Promise.resolve().then(() => {
console.log("promise");
});
queueMicrotask(() => {
console.log("microtask");
});
console.log("end");
// start, end, promise, microtask, timer
A timer schedules a task (often informally called a macrotask). Promise reactions and callbacks passed to queueMicrotask enter the microtask queue. After the current script completes, a checkpoint drains that queue. The example therefore logs start, end, promise, microtask and timer. [1][3][4]
A single FIFO queue for every task is an oversimplification. HTML defines task sources and lets the browser choose a task queue. setTimeout(fn, 0) specifies a minimum delay, not an exact execution time; when timer nesting exceeds five levels, the standard requires at least 4 ms for shorter timers. Background tabs can impose additional throttling. [1][4]
How await changes execution order
async function loadState() {
console.log("before await");
await Promise.resolve();
console.log("after await");
}
loadState();
queueMicrotask(() => {
console.log("queued later");
});
console.log("sync end");
// before await, sync end, after await, queued later
An async function executes synchronously up to its first await. Even awaiting an already fulfilled promise suspends the remainder of the function. In this example the continuation is scheduled before the later queueMicrotask, so after await precedes queued later. [5]
await Promise.resolve() is not a rendering break. The continuation remains part of the microtask checkpoint. When awaiting an actual network operation, other tasks may run while the response is pending, but computation after the response can block the main thread again.
Microtask starvation
let remaining = 3;
function scheduleNext() {
console.log(`microtask ${remaining}`);
remaining -= 1;
if (remaining > 0) {
queueMicrotask(scheduleNext);
}
}
queueMicrotask(scheduleNext);
setTimeout(() => {
console.log("timer");
}, 0);
// microtask 3, microtask 2, microtask 1, timer
While draining the queue, a microtask can schedule another microtask. The browser processes these new entries before finishing the checkpoint. All three messages in the example appear before the timer even though additional microtasks are scheduled during execution. [1][3]
An unbounded chain can prevent timers, input and rendering from progressing. Use queueMicrotask for short state batching within the same turn, not for splitting CPU-heavy work that needs to yield to the browser. An exception in a queueMicrotask callback is reported as an exception; an exception in then rejects the resulting promise. [3]
Rendering and requestAnimationFrame
function animateProgress(element, duration = 400) {
let startTime;
function update(timestamp) {
startTime ??= timestamp;
const progress = Math.min((timestamp - startTime) / duration, 1);
element.value = progress;
if (progress < 1) {
requestAnimationFrame(update);
}
}
requestAnimationFrame(update);
}
// Call with a <progress max="1" value="0"> element.
// animateProgress(document.querySelector("progress"));
A browser need not paint after every task. Rendering depends on opportunities to update the display, document visibility and workload. At 60 Hz the interval is about 16.7 ms; at 120 Hz it is about 8.3 ms. JavaScript cannot assume the entire interval is available because styles, layout and painting also require time. [1][6]
requestAnimationFrame schedules a callback before a rendering update. The example animates a progress element over 400 ms based on elapsed time rather than frame count. Each request is one-shot, so schedule the next one explicitly. A heavy callback can still cause missed frames, and callbacks may pause in hidden tabs. [6]
Splitting long work with scheduler.yield and a fallback
async function yieldToMain() {
if (typeof globalThis.scheduler?.yield === "function") {
await globalThis.scheduler.yield();
return;
}
await new Promise((resolve) => {
setTimeout(resolve, 0);
});
}
async function processInChunks(items, processItem, budgetMs = 8) {
let chunkStart = performance.now();
for (let index = 0; index < items.length; index += 1) {
processItem(items[index]);
const hasMore = index < items.length - 1;
const budgetExceeded = performance.now() - chunkStart >= budgetMs;
if (hasMore && budgetExceeded) {
await yieldToMain();
chunkStart = performance.now();
}
}
}
Expensive record processing can be split into time-based chunks using performance.now(). The example accepts a synchronous callback and yields when an illustrative 8 ms budget is exceeded and items remain. scheduler.yield() schedules a prioritized continuation; where unavailable, a timer creates a task boundary. [7][8]
Eight milliseconds is a design choice, not a standard. An individual processItem call can exceed the budget and cannot be interrupted by this helper. The caller should await the returned promise and handle errors. If data can change while yielding, use a stable input collection or cancellation and versioned results.
When to use a Web Worker
// sum.worker.js
self.addEventListener("message", (event) => {
const values = new Float64Array(event.data);
let total = 0;
for (const value of values) {
total += value;
}
self.postMessage(total);
});// main.js (module)
const worker = new Worker(new URL("./sum.worker.js", import.meta.url), {
type: "module",
});
worker.addEventListener("message", (event) => {
console.log(event.data); // 60
worker.terminate();
});
worker.addEventListener("error", (event) => {
console.error(event.message);
worker.terminate();
});
const values = new Float64Array([10, 20, 30]);
worker.postMessage(values.buffer, [values.buffer]);
For expensive computations that are difficult to split, consider a dedicated Worker. A Worker has a separate execution environment and cannot directly manipulate the DOM. The two module files in the example transfer a numeric buffer, sum its values in the Worker and send back 60. [9]
Passing an ArrayBuffer in the transfer list moves ownership, detaching the original buffer. This avoids copying the buffer for large inputs, but startup and messaging also have costs. The example terminates the one-off Worker after a response or an error; recurring jobs can reuse a Worker and identify requests by ID.
Measuring long tasks and diagnosing responsiveness
function observeLongTasks(report) {
if (!globalThis.PerformanceObserver?.supportedEntryTypes?.includes("longtask")) {
return () => {};
}
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
report({
startTime: entry.startTime,
duration: entry.duration,
});
}
});
observer.observe({ type: "longtask", buffered: true });
return () => {
observer.disconnect();
};
}
const stopObserving = observeLongTasks(console.log);
// Call stopObserving() when monitoring is no longer needed.
Tasks lasting at least 50 ms can delay interaction. Browsers that support the Long Tasks API expose longtask entries through PerformanceObserver. The example checks support, reports each task's start time and duration, and returns a function that disconnects the observer. [8][10]
Record a real interaction in Chrome DevTools Performance, inspect long blocks on the Main track and use Bottom-up to identify costly functions. Having no tasks over 50 ms does not guarantee smooth animation. The browser model also differs from Node.js, which has libuv phases and separate process.nextTick handling. Do not assume server timer ordering applies to the frontend. [11][12]
