Search code examples
javascriptjqueryeachtiming

delay $.each() function with setTimeout


Good day all.

I have this simple code:

totalTextArray = textForChatWithSeparators.split("#");    
    $.each(totalTextArray, function( index, value ) {           
    setTimeout(function(){console.log( value )},1000);
});

I expect to see in the console log, every second, the "value" logged, but instead I see all the log coming out in one block, after the delay of 1 second.

what i'm doing wrong? I'm thinking of the fact that a function inside the function could lead to some buffering problem?


Solution

  • What you're doing is

    • make a call to setTimeout n times
    • all timeouts will fire after 1000ms together

    What you would need to do if you don't want to change the structure is to increase the timeout value per iteration, like

    setTimeout(function(){ console.log( value ) },1000*index);
    

    A probably more elegant (and more correct way imo), would be to change the structure of the loop all together. Using an interval-timer like

    (function _loop( elem ) {
         console.log( elem );        
    
         if( totalTextArray.length ) {
             setTimeout( _loop.bind( null, totalTextArray.shift() ), 1000 );
         }
    }());