简体   繁体   中英

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?

What you're doing is

  • make a call to setTimeout n times
  • all timeouts will fire after 1000 ms 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 );
     }
}());

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 :

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM