Skip to content Skip to sidebar Skip to footer

Javascript Sleep With Settimeout

I'm trying to send emails with a 10 seconds delay between. I wrote this code: $(document).ready(function() { for (i = 0; i < 20; i++) { setTimeout('SendEmail(' + i +

Solution 1:

Use interval instead of loop.

Working demo:http://jsfiddle.net/xfVa9/2/

$(document).ready(function() {
    var tmr;
    var i=0;
    tmr=setInterval(function(){
        if(i<20){
            SendEmail(i);
            alert("Sent "+i)
            i++;
        }else{
            clearInterval(tmr);
        }

    },5000)

 });

Solution 2:

You should create a function which calls itself after 5 seconds

var i=0;

functionsendEmailNow() {
     SendEmail(i);
     ++i;
   if(i<20) {
        setTimeout(sendEmailNow, 5000);
    }
}

Solution 3:

What happens is that you call setTimeout 20 times, just after one another, with a timeout of 5 seconds. So naturally, all emails gets sent at once. You could change the loop to look like this:

for (i=0;i<20;i++) {
    setTimeout("SendEmail("+ i + ")",(i+1)*5000);
}

There's alot of other options though, and they'd depend on just what suits your specific problem best.

Solution 4:

First, pass a function to setTimeout.

Secondly, you'd be better off if you set the timeout for the next one in the queue after the current one is finished.

In the for loop:

sendEmail(0); // start sending first

and in the callback:

      , function(data) {
          if(id < 19) { // if next should be sentsetTimeout(function() {
                  SendEmail(id + 1);
              }, 5000);
          }
          var toAppend = "<span>     " + data + "</span>"
          $("#sentTo").append(toAppend);
      }

Solution 5:

Your loop is setting up 20 timers to wait 5 seconds, then letting them all go at once.

Try something like this:

var email_count = 20;

var sendMails = function(){
    SendEmail(email_count--);
    if(email_count > 0){
        setTimeout(sendMails, 5000);
    }
}

setTimeout(sendMails, 5000)

Post a Comment for "Javascript Sleep With Settimeout"