Question

I am thinking of using Web Workers to provide some background functionality while a user is browsing my website (that's what Web Workers are for, right?). However, I don't want to take the risk of compromising the user experience by causing laggy scrolling, unresponsive controls, etc. Web Workers are mapped on OS threads, hence I would expect some control on the priority of these threads however, as far as I know, there's no such thing in the current API. Do you know a how to accomplish this? Even with a hack?

Was it helpful?

Solution

Well, there's no API call to control low-level details like this. However, I think you should first implement what you want to do and then test if the performance hit is too great on the user experience. I'm assuming that since they did not add fine control over how the threads execute, they're probably well managed by the underlying implementation.

OTHER TIPS

Even with a hack? [...] the user uploads a photograph and the worker applies a Photoshop-like filter to it, which is pretty CPU intensive, then the worker alerts the main thread

Here's a hack.

Slow down your code. Something like this is what I am currently using for a particle simulation:

var TIME_STEP = 10,
    paused = false,
    state; // set by commands.start()

function main_loop () {
    if (paused) {
        return;
    }

    // update state incrementally. Break your process into chunks
    // for example pixels or rows of pixels
    state = ____________;

    // send state or progress to main thread
    if (finished) {
        self.postMessage(state);
    } else {
        self.postMessage(progress);
    }

    setTimeout(main_loop, TIME_STEP);
}

var commands = {
    //...functions that can be called from main thread (pause/start/cancel/etc)...
};

function message_handler (event) {
    var data = event.data;
    var command = commands[data.command];

    command.apply(this, data.args);
}

self.addEventListener('message', message_handler, false);

TIME_STEP is the time between calculations and will need to be different depending what you are doing and how long you can afford to increase it's time. One good thing about doing it this way is that you can accept pause and cancel requests between iterations.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top