Search code examples
htmlweb-worker

How to limit a number of web workers


I use web workers to calculate a bit of information in my application. And I don't want to kill the application with an increasing number of web workers so I need to limit creating new workers somehow.

My guess was that I could get a number of currently running workers. Is it possible?

Or maybe you can suggest any technique to limit creating of new ones? I was thinking about a global counter, but is it safe to use it with async workers?


Solution

  • Global counter is one way, allocating a dedicated array is another - something like for instance:

    var workers = [];
    
    function spawnWorker(srcUrl) {
    
        if (workers.length < limit) {
            var worker = new Worker(srcUrl);
            workers.push(worker);
            ...setup handlers...
            return true;
        }
        else {
            return false;
        }
    }
    

    This way you will have easy access to the workers as well.