Semaphore-like queue in javascript?

前端 未结 3 732
小蘑菇
小蘑菇 2020-12-05 08:58

I have a variable can_run, that can be either 1 or 0, and then I have a queue of functions, that should be run as soon as the variable is switched from 0<

3条回答
  •  误落风尘
    2020-12-05 09:48

    I'm not sure the best way to do this in plain JS but many libraries have Deferred implementations which are very useful for this use case.

    With jQuery:

    var dfd = $.Deferred();
    var callback = function() { 
        // do stuff
    };
    dfd.done(callback);  // when the deferred is resolved, invoke the callback, you can chain many callbacks here if needed
    dfd.resolve(); // this will invoke your callback when you're ready
    

    EDIT One of the nice things about these library supported deferreds are that they are normally compatible with Ajax events, and in turn other Deferred objects so you can create complex chains, trigger events on Ajax complete, or trigger the 'done' callback after multiple conditions are met. This is of course more advanced functionality, but it's nice to have in your back pocket.

提交回复
热议问题