50Implement a queue supporting pause, resume, and clear
mediumAbout 35 minutesCodingqueuesconcurrencyclasses
Problem
Implement a TaskQueue class that runs async tasks in order with a concurrency limit, and can be paused, resumed and cleared.
new TaskQueue({ concurrency = 1, autoStart = true }). WithautoStart: false, the queue starts paused.add(task): returns a promise for the task's result.pause(): stop starting new tasks. Tasks already running continue.resume(): start running waiting tasks again.clear(): remove every waiting task. Their promises reject with an error whosenameis"AbortError". Running tasks are not affected.size(waiting),pending(running) andisPaused.onIdle(): resolves when nothing is running and nothing is waiting.
const uploads = new TaskQueue({ concurrency: 2 });
files.forEach((file) => uploads.add(() => upload(file)));
offlineButton.onclick = () => uploads.pause();
onlineButton.onclick = () => uploads.resume();
cancelAllButton.onclick = () => uploads.clear();Requirements
- Tasks start in the order they were added.
pause()andresume()can be called any number of times in any order.- A failing task rejects only its own promise.
Try it yourself
Write your solution, run it, then submit to check it against the tests.
solution.jsJavaScript
Press Run or ⌘ Enter to execute your code.
Step-by-step
add creates a promise and pushes { task, resolve, reject } onto the queue. Keeping reject is what lets clear settle the promises of tasks that will never run.
Unlock the full solution
What's inside
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Tests
Includes 2 code listings, 4 edge cases, 4 follow-up questions.
One-time payment by UPI, card or net banking. Launch price.