Last Updated: February 25, 2016
·
1.747K
· francisc

Non-blocking code execution

The setTimeout function delays function execution asynchronously.

For the timeout interval, most browsers will default to 4ms even if you set it to 0.

var defer=function(fn){setTimeout(fn,0);}

Usage:

defer(someFunction);

defer(function()
{
    console.log('Code here is queued and not blocking the UI.');
});

Depending on what you are trying to do and browsers you are required to support, other options might be better for you.

This approach is useful for performing expensive computations or HTML rendering in chunks without blocking the UI thread from updating.

For animations, requestAnimationFrame is the best way to do it (+polyfill).

Web Workers are also very, very interesting, but browser support is so and so at the time of writing. Also, Web Workers do not have access to the DOM so you can entrust them with tasks that do not need to manipulate page elements.