且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

for循环具有延迟的功能

更新时间:2022-03-19 04:00:41

您无需在此处进行循环,它并不是链接动画的正确工具.相反,您可以使用内置的jQuery.Deferred对象.以下是如何使用它的示例.如您所见,您需要做的是使动画函数child返回延迟的对象.之后,您可以使用其then方法来确定是否需要再次调用child,直到array包含元素.

You don't need for loop here, it's not really a right tool for chained animations. Instead you can use built in jQuery.Deferred object. Below is an example of how you can use it. As you can see what you would need to do is to make your animation function child return deferred object. After that you can use its then method to decide if you need to call child one more time, until array contains elements.

var array = ['message one', 'and another', 'finally one more'];

// Invoke child until array has elements, no loops are needed here
child(array.shift()).then(function next() {
    if (array.length) {
        child(array.shift()).then(next);
    }
});


// An example of child function.
// Important part here is that this function returns deferred promise
// which is resolved once animation is complete.
function child(i) {
    var $message = $('<div class="message">' + i + '</div>');
    $message.appendTo('body');
    return $.Deferred(function() {
        $message.delay(1000).fadeOut(1000, this.resolve);
    });
}

.message {
    padding: 20px;
    background: #55E755;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

UPD..如果子功能中有一些AJAX调用,则更为简单.您只需返回类似$.get(...)的内容,这已经是一个承诺,无需使用$ .Deferred构造新的对象.

UPD. If you have some AJAX call in child function it's even simpler. You just return something like this $.get(...), it's already a promise, no need to construct new one with $.Deferred.