2015-09-25 82 views
1

我试图做一个代码为我的网站Javascript SetInterval帮助。阿贾克斯

function vind(list) { 
    for (i = 0; i < list.data.length; i++) { 
     jQuery.ajax({ 
      url: 'https://xyz-abc.com/send.php?post=123', 
      dataType: 'script', 
      success: function() { 
       volve += 1; 
       if (volve >= list.data.length) { 
       } 
      } 
     }); 
    } 
} 

所有的代码工作正常。

https://xyz-abc.com/send.php?post=123 
https://xyz-abc.com/send.php?post=123 
https://xyz-abc.com/send.php?post=123 
https://xyz-abc.com/send.php?post=123 

代码发布连续。

我想设置每个帖子之间的间隔。

https://xyz-abc.com/send.php?post=123 
wait 3 sec. 
https://xyz-abc.com/send.php?post=123 
wait 3 sec. 
https://xyz-abc.com/send.php?post=123 
wait 3 sec. 

我试过setTimeout不工作。

帮助。

+0

你似乎在你的例子中有一些失踪。 :) – toskv

+0

_set(Interval | Timeout)_对于这种情况并不理想。使用成功回调触发下一篇文章。 – lshettyl

+0

你的代码甚至没有'setTimeout'调用...显示你的尝试 –

回答

1

如果您首先要等待上一个请求完成,您可以发送第一个项目并使用setTimeout在列表的其余部分触发请求。

function vind(list) { 
 
    if (list.length > 0) { // stop if the list is empty 
 
    var firstItem = list.shift(); // nothing is done with this? 
 
    jquery.ajax('https://xyz-abc.com/send.php?post=123', { 
 
     dataType: 'script', 
 
     success: function() { 
 
     setTimeout(function() { // set a timeout with a function that will call sendData again 
 
      sendData(list); // call sendData with the rest of the list 
 
     }, 3000); // 3 seconds 
 
     } 
 
    }); 
 
    } 
 
}

您可以检查here的工作plnkr。

如果你不想等待以前的请求完成,你可以使用setTimeout来设置一系列具有不同延迟的超时。尽管如此,我不会推荐这么做。

function sendData(item) { 
 
    console.log(Date.now()); 
 
    jquery.ajax('https://xyz-abc.com/send.php?post=123', { 
 
    dataType: 'script', 
 
    success: function() {} 
 
    }); 
 
} 
 

 
function vind(list) { 
 
    for (var i = 0; i < list.length; i++) { 
 
    var currentItem = list[i]; // saving the item in the current scope now, in case the list gets modified in the meantime 
 
    setTimeout(function() { 
 
     sendData(currentItem); 
 
    }, i * 3000); // delay depends on the item's index in the list 
 
    } 
 
}
而这个解决方案 here的工作plnkr。

请记住,虽然setTimeout不能保证设置的功能将被准确地在3秒标记调用。它所做的是在3秒后将该函数放入回调队列中。这意味着由于javascript并发工作的方式将无法在3秒内使用setTimeout正确调用函数。

你可以找到一个关于事件循环如何工作的非常好的解释here。此外,还有一个由同一个人制作的工具,可以直观地显示场景here后面的情况。

+0

这不是语法或逻辑上有效的代码。 –

+0

oups,你说得对。我会解决它。 :) – toskv

+0

@FelixKling现在好了吗? :) – toskv