Subin Sebastian Subin Sebastian - 1 year ago 95
Node.js Question

Writing nested non-blocking loops in node.js

How to properly write the following set of loops in Node.Js without blocking the event loop or without causing out of memory error.

What I have tried so far includes

  • Combinations of setImmediate()/setInterval()

  • The Async module see my code here

  • Thread_a_gogo (this module is no more maintained)

The code.

for(var i = 0; i < 2000; i++)
for(var j = 0; i < 2000; j++)
for(var k = 0; k < 2000; k++)
console.log(i + ":" + j + ":" + k);

Also created a JSFiddle to play around here

Answer Source

Not really sure what your use-case is. Javascript is blocking as it's single threaded, it would have to run the loop before moving to something else.

You could for example use a generator to run each iteration on an event though.

function* ticker() {
  for(let i = 0; i < 10; i++)
    for(let j = 0; i < 10; j++)
        for(let k = 0; k < 10; k++)
            yield[i, j, k];

const gen = ticker();

setInterval(() => console.log(, 500);

console.log('I am at the end');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download