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?

Upvotes: 1

Views: 152

Answers (2)

long.luc
long.luc

Reputation: 1191

All you need is closure:

totalTextArray = textForChatWithSeparators.split("#");

$.each(totalTextArray, function(value, index) {
    setTimeout(function() {
        console.log(value);
    }, 1000 * (index + 1));
});

EDIT: I add more links about closure:

Upvotes: 1

jAndy
jAndy

Reputation: 236202

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 );
     }
}());

Upvotes: 4

Related Questions