Using Jquery promise() in 'for' loop to wait for effect to finish before starting next effect

送分小仙女□ 提交于 2019-12-12 04:34:28

问题


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 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>

回答1:


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>


来源:https://stackoverflow.com/questions/41174068/using-jquery-promise-in-for-loop-to-wait-for-effect-to-finish-before-startin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!