A solution for race conditions between browser threads.
Uses the insert-only IndexedDB add request to ensure that only one thread wins a race.
- Robust across browsers
- Fully tested
const race endRace =// will only resolve with true once until the race is ended// even across sessions, tabs, and workersif awaitconsole// allow a new winner when this tab is closedwindow
Resolves with true if this is the single winning execution and false otherwise. Uses indexedDB, so anywhere that can access the same indexedDB databases will participate in the same races (sessions, tabs, and workers for the same domain).
name specifies which race to participate in. Using a different
name allows for multiple concurrent races that don't interfere.
Synchronous function that resets the race with
name to allow another winner.
It will successfully end the race when executed in an unload event handler.
race(name) finishes on all threads before calling
endRace(name) or there will be multiple winners. Keep in mind that the minimum setTimeout() length for background tabs is 1000ms.