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?
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.
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.
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 ...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With