setTimeout and array each

Kevin picture Kevin · Jun 22, 2013 · Viewed 19.1k times · Source

I'm confused with using setTimeout and the each iterator. How can I rewrite the following so that the console outputs each name after a delay of 5 seconds? Currently the code below prints all the names at once after 5 seconds. I would like to:

1) wait 5 seconds, then print kevin
2) wait 5 seconds, then print mike
3) wait 5 seconds, then print sally

var ary = ['kevin', 'mike', 'sally'];

_(ary).each(function(person){

  setTimeout(function(){
    console.log(person);
  }, 5000);    

});

Answer

LonelyWebCrawler picture LonelyWebCrawler · Jun 22, 2013

You could create a variable called offset that makes the timer wait 5 seconds more for each person in the array, like so:

var ary = ['kevin', 'mike', 'sally'];

var offset = 0;
_(ary).each(function(person){

  setTimeout(function(){
    console.log(person);
  }, 5000 + offset);    
 offset += 5000;
});