简体   繁体   English

如何在underscore.js中的_.each循环的每次迭代中添加延迟?

[英]How can I add a delay inside each iteration of an _.each loop in underscore.js?

How can I add a delay inside each iteration of an _.each loop to space out the calling of an interior function by 1 second? 如何在_.each循环的每次迭代中添加延迟,以便将内部函数的调用空间缩短1秒?

  _.each(this.rows, function (row, i) {
      row.setChars(msg[i] ? msg[i] : ' ');
  });

You don't need extra IIFE 您不需要额外的IIFE

_.each(this.rows, function (row, i) {
    setTimeout(function () {
        row.setChars(msg[i] ? msg[i] : ' ');
    }, 1000 * i);
});

since you're not doing it in an explicit for loop. 因为你没有在明确的for循环中这样做。

Found an answer, just add a self invoking function inside the _.each loop with a timeout that continues to scale based on the number of iterations of the loop. 找到答案,只需在_.each循环中添加一个自调用函数,其超时将根据循环的迭代次数继续扩展。

Here's a working example (Edited to remove redundancy): 这是一个工作示例(编辑删除冗余):

  _.each(this.rows, function (row, i) {
      setTimeout(function () {
          row.setChars(msg[i] ? msg[i] : ' ');
      }, 1000 * i);
  });

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

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