Skip to content

Instantly share code, notes, and snippets.

@happyincent
Created January 13, 2023 18:21
Show Gist options
  • Save happyincent/8894c882c19fbded487120248dbbdcfb to your computer and use it in GitHub Desktop.
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).
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