JQuery infinite loop through .each iteration with a pause between each iteration
Basically I am looping through tweets. I want to pause for 20seconds betw开发者_如何学JAVAeen each tweet and after the last tweet I want to go back to tweet one and repeat the process infinitely.
Here is my code so far, I've tried tackling this problem by reading other peoples examples but cant quite seem to hit the nail on the head. I do keep running into the set timeout function too.
// DisplayTweets.
function displayTweets(tweets)
{
// Checks if any tweets exist.
if ($.isArray(tweets) !== false)
{
// Show error message.
$('p#tweet').text(tweets);
}
else
{
// Parse JSON into Javascript object.
var objTweets = jQuery.parseJSON(tweets);
// Loop through
$.each(objTweets, function(i, objTweet) {
//alert(objTweet.tweet);
$('p#tweet').text(objTweet.tweet);
});
}
}
Just write a function to be called with the array of values:
function displayTweets(arr){
$('p#tweet').html(arr[0]);
var i = 1;
setInterval(
function(){
$('p#tweet').html(arr[i]);
i++;
if(i >= tweets.length) i = 0;
},20000);
}
Here's a live example with the time reduced to 2 seconds for demo purpose: http://jsfiddle.net/tjAa6/
I wouldn't use $.each
as you'd have to stick a pause (perhaps with delay()
?) in the loop; setTimeout
is probably the best way to do this: just use the callback function to call a show next tweet function recursively.
showTweet(0);
function showTweet(idx)
{
$("p#tweet").text(objTweets[idx].tweet);
setTimeout(function () { showTweet((idx + 1) % objTweets.length); }, 20000);
}
精彩评论