3

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);
        }); 
    }
}
1
  • 2
    Instead of a double-negative !== false why not just use == true or just omit it altogether... if($.isArray(tweets)){...}.. it makes your code much easier to read. Commented Oct 7, 2011 at 13:14

2 Answers 2

4

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/

Sign up to request clarification or add additional context in comments.

1 Comment

thanks mate i edited slightly for my purposes but this worked a treat
2

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);
}

3 Comments

Actually, delay wouldn't work at all. And @Jamiec's answer is perfectly good too.
This should be accepted answer imo, the modulus trick to reset the index is sic.
I digress. Using this solution resulted in 'maximum stack exceeded' errors, so I went with @Jamiec's solution and seems to work fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.