0

I am working on a project and i want to send emails to users by looping through an array of emails on my server.

The items of the array (users emails) are quite much and i would like to send them emails batch by batch.

The sendMail function is called within the loop. It works now but I want to rewrite it in such a way that it will pause for 60 seconds after every 10 sends.

here is my code.

for (var i = 0; i < unsetUsers.length; i++) {
  var user = unsetUsers[i];
  var obj = {
    ---
  };
  //send mail to each one of them
  sendSetUpMail(obj); 
}

Can this be achived using for loop and setTimeout or setInterval

Kenshinman
  • 679
  • 8
  • 20
  • Possible duplicate of [Add a pause/interval to every iteration in a FOR LOOP](https://stackoverflow.com/questions/13913786/add-a-pause-interval-to-every-iteration-in-a-for-loop) – melpomene Aug 15 '17 at 23:15

1 Answers1

0

Yes, in my opinion, the best way to do this in a readable way is with a recursive function. The same functionality than your case but waiting 60 seconds for each batch.

function sendEmailsBatched(unsetUsers, offset, batchNumber) {
  var users = unsetUsers.slice(offset, offset + batchNumber);

  users.forEach(function(user) {
    var obj = {
      ---
    };
    //send mail to each one of them
    sendSetUpMail(obj);
  })

  var newOffset = offset + batchNumber;

  if (newOffset < unsetUsers.length) {
    setTimeout(function() {
      sendEmailsBatched(unsetUsers, newOffset, batchNumber);
    }, 60 * 1000);
  }
}

Now, you could call this function the first time like this:

sendEmailsBatched(unsetUsers, 0, 10)

You could also pass the timeout milliseconds to the function, or hardcode the batchNumber always to 10.

Ignacio
  • 688
  • 5
  • 17