Javascript – how to avoid blocking the browser while doing heavy work?

You could nest your calls inside a setTimeout call:

for(...) {
    setTimeout(function(i) {
        return function() { doSomethingHeavy(i); }
    }(i), 0);
}

This queues up calls to doSomethingHeavy for immediate execution, but other JavaScript operations can be wedged in between them.

A better solution is to actually have the browser spawn a new non-blocking process via Web Workers, but that’s HTML5-specific.

EDIT:

Using setTimeout(fn, 0) actually takes much longer than zero milliseconds — Firefox, for example, enforces a minimum 4-millisecond wait time. A better approach might be to use setZeroTimeout, which prefers postMessage for instantaneous, interrupt-able function invocation, but use setTimeout as a fallback for older browsers.

Leave a Comment