我有一个javascript对象,像这样:
var object = [{ id: 1, title:"xyz" }, {id: 2, title: "abc"}, {id: 3, title: "sdfs"}];现在我要做的是遍历对象,使其读取第一个id并输出"xyz",然后暂停5秒,然后遍历第二个id并输出"abc",再次暂停5秒,然后遍历第三个条目输出"sdfs",再次暂停5秒,从条目1重新开始。任何帮助都将不胜感激。
发布于 2012-06-21 03:03:53
您的基本递归函数:
function recursive(obj,idx) {
if (obj[idx]) {
alert(obj[idx].title);
setTimeout(function(){recursive(obj,idx+1);}, 5000); // milliseconds
};
};
recursive(myObject,0);或者,无限循环:
function recursive(obj,idx) {
if (obj[idx]) {
alert(obj[idx].title);
setTimeout(function(){recursive(obj,idx+1);}, 5000); // milliseconds
} else {
recursive(obj,0);
};
};
recursive(myObject,0);http://jsfiddle.net/Mezxw/
发布于 2012-06-21 03:08:32
var object = [{ id: 1, title:"xyz" }, {id: 2, title: "abc"}, {id: 3, title: "sdfs"}];
setTimeout(doNextObject, 5000);
var index = 0;
var length = object.length;
function doNextObject() {
alert(object[index].title);
index = ++index % length;
setTimeout(doNextObject, 5000);
}https://stackoverflow.com/questions/11126387
复制相似问题