There are some pros when looping in NodeJS or pure JavaScript using setTimeout instead of ‘for‘ or ‘while‘ loops.

var index = 0;
var array = [...];
var delay = 10; //example, 10 milliseconds

(function loop(){
  var entry = array[index];
  
  doSomethingWithEntry(entry,function callback(error,result){
    index++;

    if (index<array.length)
      setTimeout(loop,delay)
    else
      finalProcessingFunction();
  });
})();

Pros:

  • Delay allows a limit of loops per second thus some operations like HTTP requests to specific server won’t be blocked
  • Each call to ‘loop’ function has a specific context, so the ‘callback’ function can use outside variables related to itself for example ‘entry’
  • Callback function is call exactly in the order of ‘index’ variable
  • May be more?
Advertisements