JQuery无限循环遍历.each迭代,每次迭代之间有一个暂停

时间:2022-08-24 00:05:38

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.

基本上我正在通过推文循环。我想在每条推文之间暂停20秒,在最后一条推文之后,我想回到推文,并无限地重复这个过程。

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

2 个解决方案

#1


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/

这是一个实例,时间缩短为2秒,用于演示目的:http://jsfiddle.net/tjAa6/

#2


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.

我不会使用$ .each,因为你必须在循环中坚持暂停(可能有延迟()?); setTimeout可能是执行此操作的最佳方法:只需使用回调函数递归调用show next tweet函数。

showTweet(0);

function showTweet(idx)
{
    $("p#tweet").text(objTweets[idx].tweet);
    setTimeout(function () { showTweet((idx + 1) % objTweets.length); }, 20000);
}

#1


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/

这是一个实例,时间缩短为2秒,用于演示目的:http://jsfiddle.net/tjAa6/

#2


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.

我不会使用$ .each,因为你必须在循环中坚持暂停(可能有延迟()?); setTimeout可能是执行此操作的最佳方法:只需使用回调函数递归调用show next tweet函数。

showTweet(0);

function showTweet(idx)
{
    $("p#tweet").text(objTweets[idx].tweet);
    setTimeout(function () { showTweet((idx + 1) % objTweets.length); }, 20000);
}