创建循环设置超时 jquery 数组
Create Loop SetTimeOut Jquery Array
我正在尝试在控制台日志浏览器中创建一个带有setTimeout的循环。但它不起作用。我尝试搜索,但没有找到我需要的东西。基本上在每个循环中,在后期更新中,此打印期间的间隔为 5 秒。必须将数组带入循环。
var myArray1 = new Array( "orange", "blue", "white" );
for (var i = 0; i <= myArray1.length; i++) {
console.log("This fruit" + myArray1[i] + "is delcious!");
setTimeout(function(){ alert() }, 500); //AFTER FIVE SECONDS
setTimeout(function(){
} //CLOSE FOR
}, 5000); //AFTER FIVE SECONDS
让我举一个我使用过的例子,它可以工作,但代码太大了。我想要一种更好地理解循环的方法。
var myArray1 = new Array( "orange", "blue", "white" );
var var_time = 7000;
setTimeout(function(){
console.log("Fruit is " + myArray1[0]);
console.log("...stage 1 loading");
setTimeout(function(){
console.log("Fruit is " + myArray1[1]);
console.log( "...stage 2 loading");
setTimeout(function(){
console.log("Fruit is " + myArray1[2]);
console.log( "stage 2 finish");
alert();
console.log( "You code run perfect");
}, var_time); //stage 2
}, var_time); //stage 1
}, 500); //stage 0
不漂亮,但很简单。
var fruitColors = ["orange", "blue", "white"];
function showColor(index) {
if (index < fruitColors.length) {
console.log("Fruit is " + fruitColors[index]);
setTimeout(function() { showColor(index+1); }, 500);
}
}
setTimeout(function() { showColor(0); }, 500);
一个更漂亮但更复杂的方法是:
var fruitColors = ["orange", "blue", "white"];
fruitColors.reverse().reduce(function(m,c) {
return function() {
console.log("Fruit is " + c);
setTimeout(m, 500);
};
}, function() {})();
你可以在这里阅读reduce(MDN)。
我通常的代码是:
var myArray1 = [ "orange", "blue", "white" ];
(function loop() {
// find first element and do something with it
var current = myArray1.shift();
...
if (myArray1.length) {
setTimeout(loop, 5000);
}
})(); // start immediately
这当然会在循环运行时改变数组 - 如果这是一个问题,请复制。
更通用的版本是这样的:
function repeat(array, delay, callback, done) {
var a = array.slice();
(function loop() {
var x = a.shift();
callback(x);
if (a.length) {
setTimeout(loop, delay);
} else {
done();
}
})();
};
用法:
repeat(myArray1, 5000, function(f) {
console.log(f)
}, function() {
console.log(done);
}
相关文章:
- jQuery数组乘法
- 简单JQuery数组
- 缺陷的JQuery数组,实现不起作用
- Jquery数组-设置和加载值
- jQuery数组参数和each()
- Jquery数组查询不起作用
- 如何对jquery数组中的项执行函数
- 从 javascript 数组创建一个 Jquery 数组
- 循环JQuery数组
- 从jQuery数组或元素的对象列表中选择第N个项目
- 如何在jQuery数组中保存行的每一列的内容
- 获取jquery数组对象的第n项
- jQuery 数组迭代
- Jquery 数组通配符
- 如何从jquery数组中删除双引号
- 如何在单引号内添加每个 jquery 数组值
- 如何使用 Ajax 调用将 jQuery 数组传递到 Spring 中
- 如何将jquery数组添加到html表单中,以将复选框动态添加到对话框中
- 创建循环设置超时 jquery 数组
- 按名称查找 jquery 数组