Skip to content

Instantly share code, notes, and snippets.

@AimWhy
Created February 27, 2025 11:29
Show Gist options
  • Select an option

  • Save AimWhy/00c9096fdfcb4440223ab3b1a948d9bd to your computer and use it in GitHub Desktop.

Select an option

Save AimWhy/00c9096fdfcb4440223ab3b1a948d9bd to your computer and use it in GitHub Desktop.
class SynchronizedLock {
constructor() {
this.lock = false;
this.queue = [];
}
async getLock(timeout = 10000) {
while (this.lock) {
await new Promise((resolve) => {
this.queue.push(resolve);
setTimeout(() => {
const index = this.queue.indexOf(resolve);
if (index !== -1) {
this.queue.splice(index, 1);
console.warn('SynchronizedLock timeout');
resolve();
}
}, timeout);
});
}
this.lock = true;
}
releaseLock() {
this.lock = false;
const resolve = this.queue.shift();
if (resolve) resolve();
}
}
const synchronizedLock = new SynchronizedLock();
export default synchronizedLock;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment