Anyone familiar with JavaScript development in the browser has no doubt encountered a situation where a long-running piece of code makes the user interface unresponsive. This behavior is an artifact of JavaScript’s single-threaded nature. For example, the compute() function below contains a long-running loop simulating computationally intensive code that, even with an empty loop body, will cause a noticeable lag in an application’s response time.

function compute() {
for (var i = 0; i < 1000000000; i++) {
// perform some computation
}
}
compute();
console.log("Finished compute()");

In the browser world, a common solution to this problem is to split up computationally expensive code into smaller chunks using setTimeout(). The same technique works in Node as well, however, the preferred solution is setImmediate(). Below algorithm shows how the computationally intensive code can be broken into smaller pieces using setImmediate(). In this example, one iteration is processed each time compute() is invoked. This process allows other code to run while still adding iterations of compute() to the event loop. Note, however, that execution will be significantly slower than with the original code, because each function invocation handles only one loop iteration. A better balance of performance and responsiveness can be achieved by performing more work per function call. For example, setImmediate() could be called after every 10,000 iterations. The best approach will be dependent on your application’s needs.

var i = 0;
function compute() {
 if (i < 1000000000) {
 // perform some computation
 i++;
 setImmediate(compute);
 }
}
compute();
console.log("compute() still working…");
Share Button

Leave a Reply

Your email address will not be published. Required fields are marked *

Post Navigation