setTimeout and array each

前端 未结 6 2013
终归单人心
终归单人心 2020-12-31 04:50

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

6条回答
  •  囚心锁ツ
    2020-12-31 05:36

    You could do

    var ary = ['kevin', 'mike', 'sally'];
    
    _(ary).each(function(person, index){
    
      setTimeout(function(){
        console.log(person);
      }, index * 5000);    
    });
    

    Without increasing the timeout value, you would initialize all setTimeouts with the exact same value (thats why you see what you see).

提交回复
热议问题