Skip to content Skip to sidebar Skip to footer

Javascript - Wait For 1 Minute For Every 10 Loop?

How can I wait for 1 or 2 minute for every 10 loop? For instance, this is my working code: var dates = ['2016-08-31T23:00:00.000Z','2016-09-01T23:00:00.000Z','2016-09-02T23:00:00.0

Solution 1:

You can use setInterval and inside just for loop to increment by 10 in each interval.

var dates = ["2016-08-31T23:00:00.000Z", "2016-09-01T23:00:00.000Z", "2016-09-02T23:00:00.000Z", "2016-09-03T23:00:00.000Z", "2016-09-04T23:00:00.000Z", "2016-09-05T23:00:00.000Z", "2016-09-06T23:00:00.000Z", "2016-09-07T23:00:00.000Z", "2016-09-08T23:00:00.000Z", "2016-09-09T23:00:00.000Z", "2016-09-10T23:00:00.000Z", "2016-09-11T23:00:00.000Z", "2016-09-12T23:00:00.000Z", "2016-09-13T23:00:00.000Z", "2016-09-14T23:00:00.000Z", "2016-09-15T23:00:00.000Z", "2016-09-16T23:00:00.000Z", "2016-09-17T23:00:00.000Z", "2016-09-18T23:00:00.000Z", "2016-09-19T23:00:00.000Z", "2016-09-20T23:00:00.000Z", "2016-09-21T23:00:00.000Z", "2016-09-22T23:00:00.000Z", "2016-09-23T23:00:00.000Z", "2016-09-24T23:00:00.000Z", "2016-09-25T23:00:00.000Z", "2016-09-26T23:00:00.000Z", "2016-09-27T23:00:00.000Z", "2016-09-28T23:00:00.000Z", "2016-09-29T23:00:00.000Z", "2016-09-30T23:00:00.000Z", "2016-10-01T23:00:00.000Z"];
var c = 0var time = 2000; // 2 sec just for demofunctionloopDates() {
  for (var i = c; i < c + 10; i++) {
    if (dates[i]) {
      var date = dates[i].slice(0, 10);
      console.log(date)
    }
  }
  c += 10if (c >= dates.length) clearInterval(x)
}

loopDates()
var x = setInterval(loopDates, time)

Solution 2:

Try to put the function you do want to execute once per minute inside the setTimeout function. Also if you want to execute more than once, you should replace setTimeout with setInterval

setInterval( function() {
   dates.forEach(function(date, index) {
      counter ++;

      // Reset when you reach 10 counts.if (counter === 10) {
       counter = 0;
      }
   }
}, 120000);

Solution 3:

You can have variable for the time in timeout. Set its value to 120000 when your counter reaches 10. And make sure that you are enclosing settimeout inside IIFE (immediately invoked function expression). So for that time for particular index it'll wait for 2 minutes & then continues the loop with next indexes.

Post a Comment for "Javascript - Wait For 1 Minute For Every 10 Loop?"