簡體   English   中英

使用setTimeout延遲$ .each()函數

[英]delay $.each() function with setTimeout

大家好。

我有這個簡單的代碼:

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

我希望在控制台日志中看到每秒記錄一次“ value ”,但是相反,我看到所有日志在延遲1秒后以一個塊的形式輸出。

我做錯了什么? 我在考慮以下事實:該函數內部的函數可能會導致某些緩沖問題?

你在做什么

  • 打電話給setTimeout n
  • 所有超時將在1000毫秒后一起觸發

如果您不想更改結構,則需要做的是增加每次迭代的超時值,例如

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

可能更優雅(更正確的imo方式)是一起更改循環的結構。 使用像這樣的間隔計時器

(function _loop( elem ) {
     console.log( elem );        

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

您只需要closure

totalTextArray = textForChatWithSeparators.split("#");

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

編輯:我添加有closure更多鏈接:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM