3

I would like to wait in a loop, what is the best way to achieve this ?

Here is my actual code :

var groups = ['461', '6726', '3284', '4', '121', '11', '399', '1735', '17', '19', '1614 ];
groups.forEach(function (value) {
            myfunction(value);
        });

I would like that myfunction() being called each 5 minutes.

I would like to loop through the groups array once and waiting between each item until the end is read

What is the best way ?

mcbjam
  • 7,344
  • 10
  • 32
  • 40
  • I'm a bit confused as to what you're expecting exactly. Are you wanting to loop through the whole groups array every 5 mins or loop through the groups array once, waiting 5 minutes in between each item until the end is reached? – mscdex Apr 26 '14 at 22:04
  • Hi. I would like to loo^p through the groups array once and waiting between each item until the end is ready. – mcbjam Apr 26 '14 at 23:30
  • I'm trying to use set.interval but i don't found a way to stop it when i passed through the whole groups – mcbjam Apr 26 '14 at 23:32

2 Answers2

9

2017 Update

With es6, promises and async/await there are some nice ways to do this now. For example:

Using async/await:

const groups = [1, 2, 3, 4, 5];

function wait(milleseconds) {
  return new Promise(resolve => setTimeout(resolve, milleseconds))
}

async function send(groups) {
  for (item of groups) {
    await wait(500)
    console.log(item)
  }
}
send(groups)

Using the iterator protocol with setInterval

const groups = [1, 2, 3, 4, 5, 6]

const intv = setInterval(gen => {
  const n = gen.next()
  if (n.done) return clearInterval(intv)

  console.log(n.value)
}, 500, groups[Symbol.iterator]())
Mark
  • 90,562
  • 7
  • 108
  • 148
6

Here's a simple solution using setTimeout():

var groups = ['461', '6726', '3284', '4', '121', '11', '399', '1735', '17', '19', '1614'];
function nextGroup(idx) {
  idx = idx || 0;
  if (idx < groups.length) {
    myfunction(groups[idx]);
    setTimeout(function() {
      nextGroup(idx + 1);
    }, 5 * 60 * 1000);
  }
}
nextGroup();
jmarkmurphy
  • 11,030
  • 31
  • 59
mscdex
  • 104,356
  • 15
  • 192
  • 153