KMK KMK - 2 months ago 21
Node.js Question

Interrupt busy loop in Node.js

I have a simple busy loop in my Node.js code that has turned out to take several seconds to complete. During this time I need to perform some I/O operations, which currently are queued and all executed after the loop instead of "parallel" with the loop. I know that Node doesn't do parallel execution, so I'm looking for some way to interrupt the loop to allow Node to do other stuff.

I have tried implementing the loop with async, but that resulted in exceeding the call stack (i easily goes up to 2,000,000).

while(i < length){
if(something) sendWebSocketMessage();
//Do stuff with i
i++;
}


Any ideas?

Answer

A solution could be to write your loop like this:

(function step(){
     doSomething();
     if (length--) setImmediate(step);
})();

This way other events coming in between would be handled. If your loop is long because of a big number of iterations (vs because of long steps), you could have a partial looping in place of doSomething().

If you want to slow down your loop, in order to let more time to other tasks, you could also use setTimeout with a non null timeout:

(function step(){
     doSomething();
     if (length--) setTimeout(step, 5);
})();
Comments