我试图在一些间隔上获得每个数组链接。例如:我得到第一个链接,等待30秒,下一个链接,等待30秒另一个链接等等。下面是我的代码:
var urls = [ 'http://mylink1','http://mylink2','http://mylink3','http://mylink4'];
setInterval(function(){
urls.forEach(function(entry){
console.log(entry);
ajaxd(entry);
console.log("merge pana aici");
});
},30000);
function ajaxd(my_url) {
$.ajax({
type : "POST",
url : my_url,
success : function(msg) {
console.log(my_url);
}
});
}
问题是,30秒后我得到了所有的链接。不是第一个值,等待30秒,下一个值以此类推。
EDIT更新代码,使循环重复。
(function() {
var urls = ['http://mylink1', 'http://mylink2',
'http://mylink3', 'http://mylink4'];
// Start off at the first element.
var idx = 0;
var len = urls.length;
// Do the next link
function doNext() {
var entry = urls[idx];
console.log(idx + ":" + entry);
//ajaxd(entry);
idx++;
console.log([idx, len]);
if (idx < len) {
// Don't do anything special
} else {
// Reset the counter
idx = 0;
}
setTimeout(doNext, 300); }
// And the code needs kicked off somewhere
doNext();
}());//end of function
执行foreach将在间隔后立即遍历数组中的所有值。
一个更好的解决方案是不要迭代…
如
var counter = 0;
setInterval(function(){
if(counter < url.length){
ajaxd(url[counter]);
counter++;
}else
return;
}, 30000);
如果你仍然想使用forEach来循环数组,你可以使用setTimeout而不是setInterval。
var urls = ['http://mylink1', 'http://mylink2', 'http://mylink3', 'http://mylink4'],
interval = 2000, // = 2s
increment = 1;
urls.forEach(function(url) {
var runner = setTimeout(function() {
// Do your stuff.
console.log(url);
clearTimeout(runner);
}, interval * increment);
increment = increment + 1;
});
在闭包中使用for循环一次请求所有项
var urls = ['http://mylink1','http://mylink2','http://mylink3','http://mylink4'],
var request = function(index) {
$.ajax({
type : "POST",
url : urls[index],
success : function(content) {
console.log(content);
if (index + 1 < urls.length) {
setTimeout(function () {
request(index + 1);
}, 30 * 1000); // 30s
}
}
});
}
request(0);
你做错了尝试每30秒创建一个计数器。检查此代码:
$(document).ready(function(){
var urls = [ 'http://mylink1','http://mylink2','http://mylink3','http://mylink4'],
counter = 0;
obj = {}
obj.ajaxd = function(my_url) {
$.ajax({
type : "POST",
url : my_url,
success : function(msg) {
console.log(my_url);
}
});
}
obj.leftInterval = setInterval(function(){
if(urls[counter] != undefined){
obj.ajaxd(urls[counter]);
counter++;
}else{
counter = 0;
}
},30000);
});
使用
var urls = [ 'http://mylink1','http://mylink2','http://mylink3','http://mylink4'];
urls.reverse();
var interval = setInterval(function(){
if(urls.length == 0){
clearInterval(interval);
return;
}
var entry = urls.pop();
console.log(entry);
ajaxd(entry);
console.log("merge pana aici");
}, 30000);
注意这会改变你的数组。它将从其中删除元素,直到它为空。
EDIT:根据Andrei的评论,在clearInterval后面添加了一个返回语句:)谢谢。