Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a lock in JavaScript

How could something equivalent to lock in C# be implemented in JavaScript?

So, to explain what I'm thinking a simple use case is:

User clicks button B. B raises an onclick event. If B is in event-state the event waits for B to be in ready-state before propagating. If B is in ready-state, B is locked and is set to event-state, then the event propagates. When the event's propagation is complete, B is set to ready-state.

I could see how something close to this could be done, simply by adding and removing the class ready-state from the button. However, the problem is that a user can click a button twice in a row faster than the variable can be set, so this attempt at a lock will fail in some circumstances.

Does anyone know how to implement a lock that will not fail in JavaScript?

like image 994
smartcaveman Avatar asked Mar 17 '11 23:03

smartcaveman


People also ask

How lock is implemented in Javascript?

User clicks button B . B raises an onclick event. If B is in event-state the event waits for B to be in ready-state before propagating. If B is in ready-state , B is locked and is set to event-state , then the event propagates.

What is API lock?

The Web Locks API allows scripts running in one tab or worker to asynchronously acquire a lock, hold it while work is performed, then release it.

What is locking and its uses?

A lock is a mechanical or electronic fastening device that is released by a physical object (such as a key, keycard, fingerprint, RFID card, security token or coin), by supplying secret information (such as a number or letter permutation or password), by a combination thereof, or it may only be able to be opened from ...


1 Answers

Lock is a questionable idea in JS which is intended to be threadless and not needing concurrency protection. You're looking to combine calls on deferred execution. The pattern I follow for this is the use of callbacks. Something like this:

var functionLock = false; var functionCallbacks = []; var lockingFunction = function (callback) {     if (functionLock) {         functionCallbacks.push(callback);     } else {         $.longRunning(function(response) {              while(functionCallbacks.length){                  var thisCallback = functionCallbacks.pop();                  thisCallback(response);              }         });     } } 

You can also implement this using DOM event listeners or a pubsub solution.

like image 133
JoshRivers Avatar answered Sep 26 '22 06:09

JoshRivers