Semaphore-like queue in javascript?

javascript queue
js queue function calls
javascript action queue
javascript queue functions
javascript processing queue
javascript queue library
lock in javascript
javascript queue up function calls

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 to 1 (but only 1 such function at a time).

Right now, what I do is

var can_run=1;
function wait_until_can_run(callback) {
    if (can_run==1) {
    } else {

//...somewhere else...

wait_until_can_run( function(){
   //start running something

//..somewhere else, as a reaction to the task finishing..

It works, however, it doesn't strike me as very efficient to have about 100 timeouts continuously running. Something like semaphore would be handy in here; but in general, semaphores are not really needed in JavaScript.

So, what to use here?

edit: I have written "queue of functions" but as seen here, I don't really care about the order.

Here is a nice Queue class you can use without the use of timeouts:

var Queue = (function () {

    Queue.prototype.autorun = true;
    Queue.prototype.running = false;
    Queue.prototype.queue = [];

    function Queue(autorun) {
        if (typeof autorun !== "undefined") {
            this.autorun = autorun;
        this.queue = []; //initialize the queue

    Queue.prototype.add = function (callback) {
        var _this = this;
        //add callback to the queue
        this.queue.push(function () {
            var finished = callback();
            if (typeof finished === "undefined" || finished) {
                //  if callback returns `false`, then you have to 
                //  call `next` somewhere in the callback

        if (this.autorun && !this.running) {
            // if nothing is running, then start the engines!

        return this; // for chaining fun!

    Queue.prototype.dequeue = function () {
        this.running = false;
        //get the first element off the queue
        var shift = this.queue.shift();
        if (shift) {
            this.running = true;
        return shift;
    }; = Queue.prototype.dequeue;

    return Queue;


It can be used like so:

// passing false into the constructor makes it so 
// the queue does not start till we tell it to
var q = new Queue(false).add(function () {
    //start running something
}).add(function () {
    //start running something 2
}).add(function () {
    //start running something 3

setTimeout(function () {
    // start the queue;
}, 2000);

Fiddle Demo:

Updated to use es6 and new es6 Promises:

class Queue {  
  constructor(autorun = true, queue = []) {
    this.running = false;
    this.autorun = autorun;
    this.queue = queue;

  add(cb) {
    this.queue.push((value) => {
        const finished = new Promise((resolve, reject) => {
        const callbackResponse = cb(value);

        if (callbackResponse !== false) {
        } else {

      finished.then(this.dequeue.bind(this), (() => {}));

    if (this.autorun && !this.running) {

    return this;

  dequeue(value) {
    this.running = this.queue.shift();

    if (this.running) {

    return this.running;

  get next() {
    return this.dequeue;

It can be used in the same way:

const q = new Queue(false).add(() => {
    console.log('this is a test');

    return {'banana': 42};
}).add((obj) => {
    console.log('test 2', obj);

    return obj.banana;
}).add((number) => {
    console.log('THIS IS A NUMBER', number)

// start the sequence
setTimeout(() =>, 2000);

Although now this time if the values passed are a promise etc or a value, it gets passed to the next function automatically.


How to Correctly Manage Concurrency in JavaScript, Two easy utilities for managing JavaScript concurrency: ensure that only sync has finished: synchronizer.synchronize() // => the same promise as const collectionMutex = new Mutex(); async function set(collection: Several TS alternatives exist, but they use a queue or don't have the dispatch() option. Semaphore-like queue in javascript? (3 answers) Closed 4 years ago. I have created a Queue class in javascript and I would like to store functions as data in a queue.

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.

Parallelizing Work via a JavaScript Semaphore, This is a simple, but very effective implementation of a Semaphore , used do expensive network requests, like reading and writing to a database. _upcoming.push(fn) return p } } private _release(): void { const queue = this. Possibility of Semaphoreslim.Wait(0) (to prevent multiple execution) causing non execution. c#,asynchronous,async-await,semaphore. I tend to call this pattern the "GatedBatchWriter", i.e. the first thread through the gate handles a batch of tasks; its own and a number of others on behalf of other writers, until it has done enough work.

In addition to the other useful answers here, if you don't need the extras that those solutions provide, then an asynchronous semaphore is straightforward to implement.

It's a lower-level concept than the other options presented here though, so you may find those to be more convenient for your needs. Still, I think asynchronous semaphores are worth knowing about, even if you use higher-level abstractions in practice.

It looks something like this:

var sem = function(f){
    var busy = 0;
    return function(amount){
        busy += amount;
        if(busy === 0){

And you invoke it like this:

var busy = sem(run_me_asap);

busy is a function that maintains an internal counter of asynchronous actions that it is waiting on. When that internal counter reaches zero, it fires the function run_me_asap, which you supply.

You can increment the internal counter prior to running an asynchronous action with busy(1) and, then the asynchronous actions is responsible for decrementing the counter with busy(-1) once it is complete. This is how we can avoid the need for timers. (If you prefer, you could write sem so that it returns an object with inc and dec methods instead, like in the Wikipedia article; this is just how I do it.)

And that's all you have to do to create an asynchronous semaphore.

Here's an example of it in use. You might define the function run_me_asap as follows.

var funcs = [func1, func2, func3 /*, ...*/];
var run_me_asap = function(){

funcs might be the list of functions that you wanted to run in your question. (Maybe this isn't quite what you want, but see my 'N.B.' below.)

Then elsewhere:

var wait_until_ive_finished = function(){
        /* ... */
        /* ... */

When both asynchronous operations have completed, busy's counter will be set to zero, and run_me_asap will be invoked.

N.B. How you might use asynchronous semaphores depends on the architecture of your code and your own requirements; what I've set out may not be exactly what you want. I'm just trying to show you how they work; the rest is up to you!

And, one word of advice: if you were to use asynchronous semaphores then I'd recommend that you hide their creation and the calls to busy behind higher-level abstractions so that you're not littering your application code with low-level details.

function_queue.js � GitHub, javascript/17528961#17528961. */. var Queue = (function(){. function Queue( autorun) {. Stack and Queue in JavaScript. Stacks and Queues are linear data structures, meaning they have data elements in sequential order. Both Stacks and Queues have a worst-case of O(1) for insert and delete. How the data is added and retrieved is very important for both a Stack and a Queue.

Producer–consumer problem, In computing, the producer–consumer problem is a classic example of a multi- process synchronization problem, proposed by Edsger W. Dijkstra. The problem describes two processes, the producer and the consumer, who share a common, fixed-size buffer used as a queue. It is important to note here that though mutex seems to work as a semaphore� 7 How to output MVC / C# object to Javascript object? May 15 '12. 7 Semaphore-like queue in javascript? Jul 8 '13. View all questions and answers → Badges (43) Gold

Pend (or block) on multiple RTOS queues and semaphores in a set, Queues and semaphores must be empty when they are added to a queue set. Take particular care when adding objects such as binary semaphores which are � // Closure. Means that nothing will be passed into the global variables (on window) (function(i, s, o, g, r, a, m) { // Initial declaration of a function queue. This is what will spool the GA events to send if they're triggered // further up the page.

JavaScript Queue: How to Implement a Queue Using a JavaScript , Remove an element from the front of an array using the shift() method. It is the same as the dequeue operation. Let's implement a JavaScript queue data structure� Get started with the Azure Queue storage client library version 12 for JavaScript. Azure Queue storage is a service for storing large numbers of messages for later retrieval and processing. Follow these steps to install the package and try out example code for basic tasks. Use the Azure Queue storage client library v12 for JavaScript to: Create

  • Are you using any libraries like jQuery or Dojo? They have deferred capabilities that match your usage.
  • You need to learn about promises. See Q, or jQuery's deferreds.
  • @karel -- please do not edit questions like that...
  • Agree with @Neal, if you want post a self answer with what you would use today. Answering the question inside the question itself isn't a good idea.
  • Also @karel I updated my answer to have es6 use. Remember to pick an answer as accepted if it helped you at all :-)
  • add_function should be addFunction or simply add or push. You could also introduce unshift to add functions to the start of the queue.
  • @Shmiddty so needy :-P I do not see any issue with naming the fn add_function, it all depends on your naming conventions. And yes other methods could be added for other functions, but they are are not necessary for this answer.
  • I feel like non camel-case names in javascript are counter-intuitive, since the language itself uses camel-case for everything.
  • @Shmiddty Also, it's Crockford's standards, Yahoo's, Google's, Microsoft's and pretty much every single standard I've read.
  • The appropriateness of a naming convention is entirely dependent on the language in which you are programming. The end goal is so that you don't have to remember if something is add_function or addFunction. Since the language does everything in camelCase, that is going to be the first thing you try, intuitively.
  • There's also a standalone lib for deferred's:
  • I will definitely try this. No offense for @Neal solution, but this seems nicer.