简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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