简体   繁体   English

使用setTimeout延迟$ .each()函数

[英]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. 我希望在控制台日志中看到每秒记录一次“ value ”,但是相反,我看到所有日志在延迟1秒后以一个块的形式输出。

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 打电话给setTimeout n
  • all timeouts will fire after 1000 ms together 所有超时将在1000毫秒后一起触发

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. 可能更优雅(更正确的imo方式)是一起更改循环的结构。 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 : 您只需要closure

totalTextArray = textForChatWithSeparators.split("#");

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

EDIT: I add more links about closure : 编辑:我添加有closure更多链接:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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