Implement the Web Locks API: exclusive and shared modes, ifAvailable, steal, AbortSignal and query()
Problem
navigator.locks.request(name, callback) coordinates work across tabs and workers of one origin: only one tab refreshes the auth token, only one tab owns the WebSocket, a migration runs once. The lock is held while the callback's promise is pending. Build the same API in memory, following the Web Locks specification, as createLockManager({ clientId = "client-1" } = {}), which returns { request, query }.
const locks = createLockManager();
await locks.request("token-refresh", async () => {
const token = await refreshToken(); // other tabs wait here
save(token);
});
const result = await locks.request("leader", { ifAvailable: true }, (lock) => (lock ? "I lead" : "someone else leads"));Ref. UR-1443 · © UIRound · uiround.com/questions/implement-the-web-locks-api-exclusive-and-shared-modes-ifavailable-steal-abortsignal-and-query
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
- 3
- code listings
- 7
- edge cases
- 5
- follow-up questions
What's inside
- The full problem, with examples
- Tests that check your solution
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Card worldwide
- UPI and net banking in India
- One-time payment, nothing renews
Stuck? Take a hint
- 1Keep two structures per lock name: a FIFO queue of waiting requests and the list of locks currently held. Every change (grant, release, abort, steal) ends with one function that grants from the front of the queue while it can.
Try it in the editor
Run your code as often as you like. Submitting it to the full test suite is part of Pro.
Private, and saved in this browser as you type. All your notes are on My lists.