setTimeout and array each

前端 未结 6 2142
终归单人心
终归单人心 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:39

    array.forEach accepts a callback function which means it already creates a new function scope and as the nature of setTimeout is non-blocking which return immediately you just need to increment delay for callback function execution with every iteration:

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

    In case if you want to achieve the same with for loop you can make use of IIFE or let keyword

    IIFE example:

    var ary = ['kevin', 'mike', 'sally'];
    
    for(var i = 1; i <= ary.length; i++){
        (function(i){
            setTimeout(function(){
                console.log(ary[i - 1]);
            }, 5000 * i); 
        })(i)
    }
    

    let keyword example: [ECMAScript 6]

    var ary = ['kevin', 'mike', 'sally'];
    
    for(let i = 1; i <= ary.length; i++){
        setTimeout(function(){
            console.log(ary[i - 1]);
          }, 5000 * i); 
    }
    

提交回复
热议问题