JavaScript Interview Question #198
How should JavaScript applications handle race conditions in UI requests?
Advanced JavaScript, Practical Problems & Senior Interview Scenarios Senior Advanced
Quick Interview Answer
A UI race condition can occur when multiple asynchronous requests are in flight and an older request finishes after a newer one, overwriting the latest state. Search-as-you-type interfaces are a common example.
Detailed Explanation
A UI race condition can occur when multiple asynchronous requests are in flight and an older request finishes after a newer one, overwriting the latest state. Search-as-you-type interfaces are a common example.
Solutions include canceling obsolete requests with AbortController, assigning request sequence identifiers, or checking whether a response still belongs to the current application state before applying it. The goal is to prevent stale results from winning merely because they completed later.
Code Example
let requestVersion = 0;
async function search(query) {
const version = ++requestVersion;
const response = await fetch(
`/api/search?q=${encodeURIComponent(query)}`
);
const results = await response.json();
if (version !== requestVersion) {
return; // stale response
}
renderResults(results);
}