All timers created in loop (with setTimeout) fire at same time?

后端 未结 3 1387
滥情空心
滥情空心 2020-12-12 06:00

Can someone explain why i cant get the desired delay between each request?
They are all happening at once.

$(window).load(function(){
    $(\'a[href]\').         


        
相关标签:
3条回答
  • 2020-12-12 06:19

    The loop is run just instantly and delay every execution of conectar function for 2000ms from the time code is exectued.

    For simple case I'd use:

    $('a[href]').each(function(idx){
        ...
        window.setTimeout(function(){ conectar('HEAD', linkkhref, resp) }, idx*2000)
    
    0 讨论(0)
  • 2020-12-12 06:22

    Like Eugene said above, it's because the setTimeouts are occurring all at once. Since you're using jQuery, one thing you can do is use jQuery's Deferred objects to run all of the calls in sequence:

    $(function() {
      // dfd is our "master" deferred, which we will use to pipe the requests, one at a time
      var dfd = $.Deferred();
      // set the deferred to resolve in 2 seconds, which will start the pipeline
      window.setTimeout(dfd.resolve, 2000);
    
      $('a[href]').each(function() {
        var linkk = $(this);
        var href = linkk.attr('href');
        var req = conectar(...)
        // replace the master deferred object with one that pipes into the next request
        dfd = dfd.pipe(req);
      });
    
      dfd.done(function() { alert("All requests completed!") });
    });
    

    Of course, if all you care about is them starting execution X seconds after one another, then the other answers will work just fine. This method will allow you to effectively "chain" each one so that the next one starts as soon as the previous one completes, as well as allowing you to signal when all of them are done (using dfd.done).

    0 讨论(0)
  • 2020-12-12 06:24

    Becase setTimeout for all links is called at once. If you want to delays between call you need to do something like this:

     var delay = 2000;
     $('a[href]').each(function(){
        var linkk = $(this)
        var linkkhref = linkk.attr('href');
    
        window.setTimeout(function(){ conectar('HEAD', linkkhref, resp) }, delay);
        delay += 2000;
        ....
    
    0 讨论(0)
提交回复
热议问题