Search code examples
javascripteventslockingdom-eventsdeadlock

How to implement a lock?


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?


Solution

  • 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.