我有一个我认为是一个简单的问题需要解决(从来没有!)我试图循环遍历我制作的 javascript 数组中的 URL 列表,加载第一个,等待 X 秒,然后加载第二,继续,直到我重新开始。 我让数组和循环工作了,问题是,但是我尝试使用 setInterval 或类似的方法实现“等待”,我遇到了结构问题,因为循环在后台继续进行。
我了解 setTimeOut 和 setInterval,但无法以有效的方式格式化代码。我是 javascript 新手,因此经常犯各种愚蠢的错误,并且非常感谢能够理解如何最好地构建它,以及一些工作示例!
我尝试像这样编写代码:
$(document).ready(function(){
// my array of URL's
var urlArray = new Array();
urlArray[0] = "urlOne";
urlArray[1] = "urlTwo";
urlArray[2] = "urlThree";
// my looping logic that continues to execute (problem starts here)
while (true) {
for (var i = 0; i < urlArray.length; i++) {
$('#load').load(urlArray[i], function(){
// now ideally I want it to wait here for X seconds after loading that URL and then start the loop again, but javascript doesn't seem to work this way, and I'm not sure how to structure it to get the same effect
});
}
}
});
最佳答案
您应该使用 setTimeout()
或 setInterval()
而不是 while
循环,并在达到计数器限制时手动中断.
var count = 0;
// Function called by setInterval
function loadIt() {
$('#load').load(urlArray[count], function(){
// Do your thing
});
count++; // Increment count
if(count == urlArray.length) {
count = 0;
}
}
loadIt(); // Call the function right away to get it going
var interval = setInterval(loadIt, 5000); // then call it every five seconds
编辑:
进行编辑以将计数器维护从 load()
回调中删除。
编辑:
每次设置计数
的更漂亮的方法如下:
count = (count == urlArray.length) ? 0 : count + 1;
关于javascript - 在 Javascript JQuery 中加载 ajax 内容后循环和暂停,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3008130/