JavaScript/PHP中每个foreach之间的延迟

3

我有一个从数据库中获取个人信息的函数,然后在jquery中遍历这些信息并进行动画处理。问题是...我发现这个问题非常普遍,就是javascript会在瞬间遍历所有项目,并且延迟将应用于所有项目。

我已经在stackoverflow上搜索到一些相关参考资料,但是没有一个可以与下面的代码配合使用。任何想法都将不胜感激。

$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等待,但我认为这导致了一个无限循环......不确定......页面没有加载。
我希望有人能指点我正确的方向。
理想情况下,它会动画化几个......等待......然后再做一些......
提前感谢。

你尝试过使用jQuery的delay吗? - kobe
1个回答

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接