Javascript semaphore / test-and-set / lock?

前端 未结 6 883
无人共我
无人共我 2020-12-13 23:09

Is there such a thing as an atomic test-and-set, semaphore, or lock in Javascript?

I have javascript invoking async background processes via a custom protocol (the b

6条回答
  •  温柔的废话
    2020-12-13 23:52

    First of all, while it is true that javaScript is single threaded, it is NOT true that no serialization mechanism is ever required by a javaScript application.

    A simple example, is when a submit button should fade out for a set amount of time during which an Ajax request to a server is working. When the asynchronous Ajax request successfully completes then a message should appear where the button used to be.

    While it would be nice to be able to cancel the button's fadeout and simply set its style to "display: none", as soon as the Ajax request completes, that is not possible in jQuery. Also, a solution could use Events to synchronize the two simultaneous activities, but that is essentially overkill for a simple problem.

    A low-tech solution is to poll a lock and when the fadeout completes it is unlocked but the "server done" message is NOT displayed until the success callback, as set by $.post, executes.

    var gl_lock;
    var gl_selfID;
    
    function poll_lock(message) {
         if (gl_lock === 0) {
              $('#output').text(message).fadeIn(200);
              window.clearInterval(gl_selfID);
         }
     } // end of poll_lock
    
     function worker() {
    
         // no one gets in or out
         gl_lock = 1;
    
         $.post(..., data,function() { 
               gl_selfID = window.setInterval(poll_lock, 40, data.message);
          }, "json");
    
         // end of fadeout unlock the semaphore
         $('#submit-button').fadeOut(400, function() { gl_lock = 0; });
    
      } // end of worker
    

    Finally, I think this is more detailed answer, along the lines previously suggested in this discussion by perrohunter.

提交回复
热议问题