Created
January 13, 2023 18:21
-
-
Save happyincent/8894c882c19fbded487120248dbbdcfb to your computer and use it in GitHub Desktop.
Lock then run the Promise only in one window/tab with Web Locks API (native/polyfill).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if (!window.isSecureContext) import("navigator.locks"); | |
async function lockThenRun<T>(name: string, callback: (lock: Lock | null) => Promise<T>) { | |
return await window.navigator.locks | |
.request(name, { ifAvailable: true }, async (lock) => { | |
if (lock === null) throw new DOMException("The lock was not granted."); | |
await new Promise((resolve) => setTimeout(resolve, Math.random() * 100)); | |
return lock; | |
}) | |
.then(callback) | |
.catch(() => null); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment