【问题标题】:Executing series of functions inside timeout loop在超时循环中执行一系列函数
【发布时间】:2013-10-01 23:38:29
【问题描述】:

我想执行一系列函数调用,每个函数调用都会在屏幕上发布一条 jGrowl 消息。当我立即执行此操作时,屏幕上不会显示任何内容。当我尝试在超时循环中设置延迟时,所有调用都会立即执行。

代码如下:

var tests = [];
tests.push("$.notification('this is a test');");
tests.push("$.notification('this is a test', 7);");
tests.push("$.notification({ message: 'this is a test', code: 'warning', sticky: false });");
tests.push("$.diagnostic({ message: 'click OK to continue', alert: true });");
tests.push("$.notification.erase();");

// 为什么这不起作用? //>
功能等待(毫秒){ var 完成 = 假; 而(!完成){ 设置超时(函数(){ 完成=真; }, 小姐) } }

这是控制台:

16.30.6.265: : Executing test[0]: $.notification('this is a test');
16.30.6.266: : Executing test[1]: $.notification('this is a test', 7);
16.30.6.266: : Executing test[2]: $.notification({ message: 'this is a test', code: 'warning', sticky: false });
16.30.6.266: : Executing test[3]: $.diagnostic({ message: 'click OK to continue', alert: true });
16.30.6.266: : Executing test[4]: $.notification.erase()

;

时间戳以毫秒为单位,因此不会发生延迟。

【问题讨论】:

  • (function(index){…}); 在做什么?您是否忘记将其作为 IEFE 调用?如果是这样,index 应该用来做什么?

标签: javascript settimeout


【解决方案1】:

问题是setTimeout 没有“堆叠”。也就是说,当您调用setTimeout 后跟另一个setTimeout 时,JavaScript 不会执行第一个,然后执行第二个。它说“哦,嘿,从现在开始这两次超时”。如果该时间相同,那么它们将同时执行(或彼此在微秒内;也不应依赖一个在另一个之前执行)。

您的问题有两种解决方案。您可以每次增加超时,以便事件以交错的方式发生,或者您可以链接超时,以便第一个触发第二个,第二个触发第三个,依此类推。

我认为第一种方法(增加超时)可能会产生一个更简单和更清洁的解决方案,所以我将在这里介绍:

delay = 500;   // half a second between messages
for (var i = 0; i < tests.length; i++) {
    t = tests[i];
    $.diagnostic('Executing test[' + i + ']: ' + t);
    (function (index,t) {
        setTimeout(function() {
            eval(t);
        }, index*delay);
    })(i,t);
}

顺便说一句,强烈建议不要使用eval:它只会导致痛苦和难以维护的代码。最好使用匿名函数;根据我对您的问题的了解,您没有理由不能这样做。

【讨论】:

  • 感谢您的反馈。我明天会看看这个。至于eval,我同意,但是这段代码只在我的单元测试方法中,没有在任何主流代码中。
猜你喜欢
  • 2018-04-05
  • 1970-01-01
  • 2012-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多