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

徘徊边缘 提交于 2019-12-22 05:40:52

问题


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(this.rows, function (row, i) {
      row.setChars(msg[i] ? msg[i] : ' ');
  });

回答1:


You don't need extra 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.




回答2:


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.

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);
  });


来源:https://stackoverflow.com/questions/24502221/how-can-i-add-a-delay-inside-each-iteration-of-an-each-loop-in-underscore-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!