在"for"循环中使用Jquery promise()等待效果完成,然后再开始下一个效果 [英] Using Jquery promise() in 'for' loop to wait for effect to finish before starting next effect

查看:336
本文介绍了在"for"循环中使用Jquery promise()等待效果完成,然后再开始下一个效果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么下面的代码在开始循环中的下一个动画之前不等待动画完成.

I want to know why the following code does not wait for an animation to finish before starting the next animation in the loop.

由于某种原因,循环创建的所有元素会立即显示并同时淡入.从代码中,我希望第一个元素将在循环的第一次迭代完成之前逐渐消失,然后"for"循环的第二次迭代将在下一个元素中逐渐消失,依此类推.

For some reason all the elements created by the loop are displayed at once and faded in simultaneously. From the code, I would expect that the first element would finish fading in before the first iteration of the loop finishes then the second iteration of the 'for' loop would fade in the next element and so on..

在创建混乱的代码之前,我不想使用回调,而且我想使用将使用动态数据的循环-动画的数量会有所不同.

I do not want to use callbacks before this creates messy code and also I want to use a loop which will use dynamic data -- the number of animations will vary.

<div id="container"></div>

<script>
var data = [1,2,3,4]; 

for(var i = 0; i < data.length; i++){
    $("#container").append("<h1>"+data[i]+"</h1>").hide().show("fade",2000);
    $("#container").promise().done(function(){console.log('sweet');});
}
</script>

推荐答案

Promise不会神奇地终止您的for循环,它们所做的只是提供一种链接回调的方法.您一次要制作所有动画,然后等待它们同时完成.要按顺序获取它们,可以使用

Promises do not magically halt your for loop, all they do is provide a way to chain callbacks. You were doing all your animations at once, and waited for them concurrently to finish. To get them in sequence, you can use

<div id="container"></div>
<script>
[1,2,3,4].reduce(function(prev, d, i) {
    return prev.then(function() {
        console.log('start', i)
        return $("<h1/>", {text: d})
        .appendTo("#container")
        .hide().show("fade",2000) // I assume you meant to animate the h1, not the container
        .promise();
    }).then(function() {
        console.log('sweet! end', i);
    });
}, $.when());
</script>

这篇关于在"for"循环中使用Jquery promise()等待效果完成,然后再开始下一个效果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆