Skip to content
Advertisement

Async task manager with maximum number of concurrent “running” tasks

I am trying to implement two classes that can deal with asynchronous tasks in JavaScript:

  • Class Task: mimics the execution of a task with setTimeout. Once the timer expires, the task is considered completed.
  • Class TaskManager: has a capacity parameter to limit the numbers of tasks that can be executing in parallel.

I thought if I could just call the loop function recursively, just to keep checking if one job is done, I could proceed to the next job. But this leads immediately to a “Maximum call stack size exceeded” error.

Can someone explain how I can fix this?

JavaScript

Advertisement

Answer

You should not implement the busy loop, as that will block the event loop and so no user UI events or setTimeout events will be processed.

Instead respond to asynchronous events.

If you let the setTimeout callback resolve a Promise, it is not so hard to do.

I modified your script quite drastically. Here is the result:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement