首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >函数之间的延迟

函数之间的延迟
EN

Stack Overflow用户
提问于 2012-08-15 17:53:03
回答 1查看 214关注 0票数 2

这是我的代码片段。

代码语言:javascript
复制
    function customFadeIn () {
    $("img.imgKit").each(function(index) {
        $(this).delay(1000*index).fadeIn("slow");
    });
    console.log("one runs");
}

function customFadeOut () {
    $("img.imgKit").each(function(index) {
        $(this).delay(1000*index).not(document.getElementById('card-6')).fadeOut("slow" , function () {
            $("#card-6").delay(1000).rotate({angle:0});
        });
    });
    console.log("two runs");
}

我希望customFadeOut只在customFadeIn完成后运行,因此我这样调用它

代码语言:javascript
复制
customFadeIn();
customFadeOut();

但是它没有起作用,我想我在这里做错了什么,如果能帮上忙的话会很有帮助。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-08-15 17:56:50

您可以使用jQuerys Deferred / promise对象。动画也“继承”这些对象,你可以应用jQuery.when()来拍摄多个完成的承诺。

有几种方法可以为此重新构造代码,其简单实现可能如下所示:

代码语言:javascript
复制
(function() {
    var promises = [ ];

    function customFadeIn () {
        $("img.imgKit").each(function(index) {
             promises.push( $(this).delay(1000*index).fadeIn("slow").promise() );
        });
    }

    function customFadeOut () {
        jQuery.when.apply( null, promises ).done(function() {
            $("img.imgKit").each(function(index) {
                $(this).delay(1000*index).not(document.getElementById('card-6')).fadeOut("slow" , function () {
                    $("#card-6").delay(1000).rotate({angle:0});
                });
            });
            console.log("two runs");
        });
    }
}());

如果我没有做错任何事情,customFadeOut会设置一个侦听器,在运行自己的代码之前等待所有动画/承诺完成。最后,您甚至不必显式地调用.promise()方法,jQuery应用了一些白魔法,将该节点与内部的promise链接起来。

演示http://jsfiddle.net/RGgr3/

看起来我做的一切都是正确的;)

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11967263

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档