2011-05-29 399 views
3

我有一個函數,從數據庫中獲取個人,然後在jquery中運行它們,爲它們製作動畫。我看到的問題非常普遍,那就是JavaScript在瞬間完成所有項目並延遲應用於所有項目。 我有搜索stackoverflow,並找到了一些這方面的參考,但沒有與我的代碼下面的工作。任何想法將不勝感激。每個foreach之間的延遲javascript/php

$individuals = $wpdb->get_results("SELECT * FROM wp_sisanda_individualsponsors"); 

?> 

<script type="text/javascript"> 
function individual_sponsors() { 
    var individuals = <?php echo json_encode($individuals) ?>; 
    individuals.sort(function() { return 0.5 - Math.random() }); 
    jQuery.each(individuals, function (i, elem) { 
     var topRand = Math.floor(Math.random()*301); 
     var leftRand = Math.floor(Math.random()*301); 
     var startLeftRand = Math.floor(Math.random()*301); 
     jQuery('.individuals').append('<div id="'+ elem.id + '" class="indiv" style="position: absolute; bottom: -70px; left:' + startLeftRand +'px;">' + elem.name + '</div>'); 
     jQuery('#' + elem.id).animate({ 
      top: -100, 
      left: Math.floor(Math.random()*301) 
     },20000 + Math.floor(Math.random()*50000)); 
    }); 
    } 
</script> 

正如你可以看到,該項目獲得一個隨機水平起始位置和結束位置,隨機速度,這個效果很好,但仍有項目的主要羣聚。

我試圖限制最初請求的數量 - 隨機選擇一些,然後重複調用函數與PHP之間等待,但我認爲,這造成了一個ifinite循環...不知道...頁wasn加載。

我希望有人能指出我正確的方向。

理想的情況下,將動畫數...等待...然後做更多一些......提前

感謝

+0

你嘗試jQuery的延遲 – kobe 2011-05-29 17:47:09

回答

1

一個PHP等待不會幫助你的PHP在服務器上執行在任何事情發送到客戶端之前(JavaScript執行的地方)。如果你想動畫一些,稍等一會,然後進行動畫處理更多一些,直到你完成,那麼你可以使用setTimeout

var current = 0; 
function animateSome() { 
    // Animate a few (starting at individuals[current]) and 
    // update current with the array index where you stopped. 
    // ... 

    // If there's anything left to do, start a timer to animate 
    // the next chunk of individuals. 
    if(current < individuals.length) 
     setTimeout(animateSome, 250); 
} 
animateSome();