Misha Slyusarev
Misha Slyusarev

Reputation: 1383

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?

Upvotes: 0

Views: 81

Answers (1)

user1693593
user1693593

Reputation:

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.

Upvotes: 1

Related Questions