Pause And Resume An Async Task Queue

A concurrency-capped task queue gains pause() to hold new starts, resume() to continue them, and drain() that resolves once nothing runs or waits.

JavascriptResilience

Code

javascriptsnippet
60 lines
// A task queue that starts work only while running: pause() holds new
// starts, resume() continues, drain() waits until everything settles.
class TaskQueue {
  #pending = [];
  #running = 0;
  #paused = false;
  #drainResolve = null;

  constructor(maxRunning = 2) {
    this.maxRunning = maxRunning;
  }

  add(task) {
    this.#pending.push(task);
    this.#startNext();
  }

  #startNext() {
    if (this.#paused || this.#running >= this.maxRunning) return;
    const task = this.#pending.shift();
    if (!task) return;
    this.#running++;
    task().finally(() => {
      this.#running--;
      if (this.#running === 0 && this.#pending.length === 0 && this.#drainResolve) {
        const resolve = this.#drainResolve;
        this.#drainResolve = null;
        resolve();
      }
      this.#startNext();
    });
  }

  pause() { this.#paused = true; }
  resume() { this.#paused = false; this.#startNext(); }
  get pending() { return this.#pending.length; }
  get running() { return this.#running; }
  // Resolves once nothing is running and nothing is waiting.
  drain() {
    if (this.#running === 0 && this.#pending.length === 0) return Promise.resolve();
    return new Promise((resolve) => { this.#drainResolve = resolve; });
  }
}

const queue = new TaskQueue(2);
const makeTask = (name, ms) => async () => {
  await new Promise((r) => setTimeout(r, ms));
  console.log(`${name} done (running=${queue.running}, pending=${queue.pending})`);
};

queue.add(makeTask('a', 30));
queue.add(makeTask('b', 20));
queue.add(makeTask('c', 10));
queue.pause(); // d and e wait even though concurrency slots look free.
queue.add(makeTask('d', 5));
queue.add(makeTask('e', 5));
console.log('paused: pending=' + queue.pending + ' running=' + queue.running);
queue.resume();
await queue.drain();
console.log('drained');

Output

Captured from a sandboxed run of this snippet in the build pipeline.

paused: pending=3 running=2
b done (running=2, pending=3)
a done (running=2, pending=2)
c done (running=2, pending=1)
d done (running=2, pending=0)
e done (running=1, pending=0)
drained

How it works

Pause And Resume An Async Task Queue keeps everything in the class TaskQueue and the function makeTask.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

The return value is newly constructed — inputs are never handed back.

What to watch for

  • The import surface (if any) is all standard library, all versioned with the language itself.
  • The guard this.#paused || this.#running >= this.maxRunning short-circuits the flow with an early return when its condition holds.

Using it

Signature: const makeTask = (name, ms)

Output lines are prefixed (paused: pending=, drained), making each step’s effect easy to spot.

Key statements

return new Promise((resolve) => { this.#drainResolve = resolve; });
await new Promise((r) => setTimeout(r, ms));
if (this.#running === 0 && this.#pending.length === 0) return Promise.resolve();

Interactive Tools for This Topic

FAQ

Does `makeTask` modify its input?
No. Nothing passed in is written to, which makes the call safe on shared data.
Are there dependencies to manage?
No. There are no dependencies to declare or install. The file defines `makeTask` at load time.