Reputation: 648
I have a javascript object like so:
var object = [{ id: 1, title:"xyz" }, {id: 2, title: "abc"}, {id: 3, title: "sdfs"}];
Now what I want to do is go through the object such that it would read the first id and output "xyz", then pause for 5 seconds, then go through the second id and output "abc", pause for 5 seconds again then go through the third entry output "sdfs", pause for 5 seconds yet again and start all over from entry 1. I want this to go on indefinitely. Any help would be appreciated.
Upvotes: 1
Views: 195
Reputation: 92893
Your basic recursive function:
function recursive(obj,idx) {
if (obj[idx]) {
alert(obj[idx].title);
setTimeout(function(){recursive(obj,idx+1);}, 5000); // milliseconds
};
};
recursive(myObject,0);
Or, to loop infinitely:
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);
Upvotes: 5
Reputation: 32273
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);
}
Upvotes: 0