javascript sleep with SetTimeout

前端 未结 6 2045
粉色の甜心
粉色の甜心 2020-12-21 18:34

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++) {
        setTi         


        
相关标签:
6条回答
  • 2020-12-21 19:12

    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)
    
    0 讨论(0)
  • 2020-12-21 19:23

    You should create a function which calls itself after 5 seconds

    var i=0;
    
    function sendEmailNow() {
         SendEmail(i);
         ++i;
       if(i<20) {
            setTimeout(sendEmailNow, 5000);
        }
    }
    
    0 讨论(0)
  • 2020-12-21 19:28

    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 sent
                  setTimeout(function() {
                      SendEmail(id + 1);
                  }, 5000);
              }
              var toAppend = "<span>     " + data + "</span>"
              $("#sentTo").append(toAppend);
          }
    
    0 讨论(0)
  • 2020-12-21 19:29

    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)
    
     });
    
    0 讨论(0)
  • 2020-12-21 19:34

    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.

    0 讨论(0)
  • 2020-12-21 19:39
    1. Avoid jQuery. Learn JavaScript.
    2. var i = 0; (otherwise leak into outer scope or runtime error)
    3. Extra closure:

      window.setTimeout(
        (function (j) {
           return function () {
             sendEmail(j);
           };
         }(i)),
        i * 10000);
      
    4. sendEmail (code style: not a constructor)
    5. You really want to escape $id in the server-side code to prevent SQL injection.
    0 讨论(0)
提交回复
热议问题