node js non blocking for loop

Viewed 3230

Please check if my understanding about the following for loop is correct.

for(let i=0; i<1000; i){
  sample_function(i, function(result){});
}

The moment the for loop is invoked, 1000 events of sample_function will be qued in the event loop. After about 5 seconds a user gives a http request, which is qued after those "1000 events". Usually this would not be a problem because the loop is asynchronous. But lets say that this sample_function is a CPU intensive function. Therefore the "1000 events" are completed consecutively and each take about 1 second. As a result, the for loop will block for about 1000 seconds.

Would there be a way to solve such problem? For example would it be possible to let the thread take a "break" every 10 loops? and allow other new ques to pop in between? If so how would I do it?

1 Answers

Try it this:

 for(let i=0; i<1000; i++)
 {
    setTimeout(sample_function, 0, i, function(result){});
 }

or

function sample_function(elem, index){..}

var arr = Array(1000);
arr.forEach(sample_function);
Related