JavaScript asynchronous race condition
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
An asynchronous race condition happens when the final state of your JavaScript code depends on which async operation finishes last, not on which one should logically win. These bugs are common in search boxes, form autosave, and any UI that starts a new request before the previous one is finished.
A Simple Race Condition Example
Imagine a search field that fetches results every time the user types. If the request for an older query finishes after the request for a newer query, stale results can overwrite the correct ones.
If the cat request is slower than the caterpillar request, it may finish later and replace the newer results with older data.
Fix It with a Request Token
One common fix is to assign each request a version number and ignore responses that are no longer current.
Now only the latest request is allowed to update the UI. Older responses still finish, but they are ignored.
Cancel Old Requests with AbortController
If the environment supports it, cancelling obsolete requests is even better because it reduces wasted work.
This pattern is useful for typeahead inputs and other interfaces where only the newest request matters.
Shared State Is the Real Problem
The deeper issue is not that JavaScript is multithreaded in the same way as some backend languages. The problem is that multiple asynchronous tasks are competing to update shared state such as UI data, cache entries, or a single object in memory.
Once you recognize the shared state, the fix becomes clearer. You either serialize updates, attach ownership to each request, or make outdated work unable to commit its result.
Serialize Work When Order Matters
Some operations should not overlap at all. For example, if you autosave a document and each save must happen in order, it may be better to queue writes rather than let them race. In those cases, the right fix is not cancellation but explicit sequencing.
This pattern ensures each save starts only after the previous save has completed.
Practical Strategies
A few habits reduce race conditions significantly:
- Keep async functions small and explicit about what state they update.
- Prefer immutable result replacement over mutating shared objects in many places.
- Tag requests, cancel outdated work, or queue operations when order matters.
- Test with artificial delays so out-of-order completion happens in development, not only in production.
Common Pitfalls
- Assuming requests will finish in the same order they were started.
- Updating shared state from multiple async functions without ownership checks.
- Catching every error and accidentally hiding
AbortErrorversus real failures. - Fixing the UI symptom while leaving the underlying shared-state race unresolved.
Summary
- An async race condition appears when completion order, rather than intended logic, controls the final state.
- Search requests and autosave flows are common places where this bug appears.
- Use request tokens or
AbortControllerto stop stale responses from overwriting newer state. - Focus on the shared state being updated, because that is where the race actually happens.
- Reproducing delayed or out-of-order responses is one of the fastest ways to debug these issues.
Related reading
- Javascript background loop
- JavaScript callbacks for asynchronous functions is there any pattern to differentiate between return value and exception?
- javascript class property not set in success function of ajax call
- JavaScript generator-style async
- JavaScript Calculate the nth root of a number
- Javascript call() & apply() vs bind()?
- Javascript console.log in an iOS UIWebView
- Javax validation on nested objects - not working
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.