How to implement a lock in JavaScript

前端 未结 8 920
青春惊慌失措
青春惊慌失措 2020-12-04 07:49

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

相关标签:
8条回答
  • 2020-12-04 08:31

    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.

    0 讨论(0)
  • 2020-12-04 08:37

    Here's a simple lock mechanism, implemented via closure

    const createLock = () => {
    
        let lockStatus = false
    
        const release = () => {
            lockStatus = false
        }
    
        const acuire = () => {
            if (lockStatus == true)
                return false
            lockStatus = true
            return true
        }
        
        return {
            lockStatus: lockStatus, 
            acuire: acuire,
            release: release,
        }
    }
    
    lock = createLock() // create a lock
    lock.acuire() // acuired a lock
    
    if (lock.acuire()){
      console.log("Was able to acuire");
    } else {
      console.log("Was not to acuire"); // This will execute
    }
    
    lock.release() // now the lock is released
    
    if(lock.acuire()){
      console.log("Was able to acuire"); // This will execute
    } else {
      console.log("Was not to acuire"); 
    }
    
    lock.release() // Hey don't forget to release

    0 讨论(0)
提交回复
热议问题