Question

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 ?

Was it helpful?

Solution 2

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

OTHER TIPS

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]())

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top