Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery infinite loop through .each iteration with a pause between each iteration

Tags:

jquery

each

Basically I am looping through tweets. I want to pause for 20seconds between 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);
        }); 
    }
}
like image 393
Max Silva Avatar asked Jan 29 '26 05:01

Max Silva


2 Answers

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/

like image 60
Jamiec Avatar answered Jan 30 '26 21:01

Jamiec


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);
}
like image 37
meloncholy Avatar answered Jan 30 '26 21:01

meloncholy