当函数完成后执行代码

4

我在代码中有一个函数,用于动画化多个元素。我想要的是在这个函数完成后执行一系列的代码。

比如说我有以下代码:

executeMyAnimationFunction();

// Execute this code AFTER executeMyAnimationFunction() has completed
alert('test');

到目前为止,我尝试使用setTimeout,但这似乎不是很可靠。我还试过使用.promise(),但它似乎也无法正常执行:

$(executeMyAnimationFunction()).promise().done(function () {
    alert('test');
});

然而我承认我一直在错误地使用它。在jQuery网站上的演示中,似乎promise()被用于正在被动画处理的元素。我尝试像这样做:

$('#myAnimatedElement').promise().done(function () {
    alert('test');
});

在某些情况下,它似乎有效,但在其他情况下则无效。我想知道使用promise()是否可靠?

基本上,我现在遇到了一个问题,即如何做到这一点。我只想等待函数完全执行(该函数仅对一组元素进行动画处理),然后继续执行我的代码。

是否有使用jquery/javascript的简单方法我可能忽略了吗?

谢谢

编辑:为了更详细地展示我的问题,这是我正在使用的确切代码:

<script>
        $(function () {

            $(window).bind('hashchange', function (e) {
                if ($(':animated').length) {
                    return false;
                }

                var section = $.param.fragment();
                var current = $('#content').children(':visible').attr('id');

                $('a').removeClass('active');                

                // If this is the first load of the page, then animate in the initial content
                if (section === '') {                    
                    if (current === 'reception') {
                        animateContentIn("reception");                        
                    }
                    else {                        
                        $('a[href="#' + section + '"]').addClass('active');

                        // Animate out existing content
                        animateContentOut(current);

                        setTimeout(function () {
                            animateContentIn("reception");
                        }, 1000);
                    }
                }
                else {
                    // Otherwise find the current page content and animate out
                    animateContentOut(current);

                    setTimeout(function () {
                        animateContentIn(section);
                    }, 1000);
                }               
            })

            // Since the event is only triggered when the hash changes, we need to trigger
            // the event now, to handle the hash the page may have loaded with.
            $(window).trigger('hashchange');
        });       

        function animateContentIn(activePage) { 
            // Now animate in the new content
            switch (activePage) {
                case "floorspace":
                    animateFloorspaceElementsIn();
                    break;
                case "reception":
                    animateReceptionElementsIn();
                    break;
            }
        }

        function animateContentOut(currentPage) {
            // Now animate in the new content
            switch (currentPage) {
                case "floorspace":                    
                    animateFloorspaceElementsOut();
                    break;
                case "reception":
                    animateReceptionElementsOut();
                    break;
            }
        }

        function animateReceptionElementsIn() {
            $('#reception').show();

            $('#reception .title').animate({
                bottom: 520
            }, 400);

            $('#reception .tile1').animate({
                bottom: 504
            }, 600);

            $('#reception .tile2').animate({
                bottom: 504
            }, 700);

            $('#reception .hero').animate({
                bottom: 40
            }, 1000);

            $('#reception .content1').animate({
                bottom: 8
            }, 400);

            $('#reception .content2').animate({
                bottom: 8
            }, 500);
        }

        function animateReceptionElementsOut() {
            $('#reception .title').animate({
                bottom: -56
            }, 400);

            $('#reception .tile1').animate({
                bottom: -136
            }, 600);

            $('#reception .tile2').animate({
                bottom: -152
            }, 700);

            $('#reception .hero').animate({
                bottom: -464
            }, 1000, function () {
                $('#reception').hide();
            });

            $('#reception .content1').animate({
                bottom: -112
            }, 400);

            $('#reception .content2').animate({
                bottom: -104
            }, 500);
        }

        function animateFloorspaceElementsIn() {
            $('#floorspace').show();

            $('#floorspace .title').animate({
                bottom: 520
            }, 400);

            $('#floorspace .tile1').animate({
                bottom: 504
            }, 600);

            $('#floorspace .tile2').animate({
                bottom: 504
            }, 700);

            $('#floorspace .hero').animate({
                bottom: 40
            }, 1000);

            $('#floorspace .content1').animate({
                bottom: 8
            }, 400);

            $('#floorspace .content2').animate({
                bottom: 8
            }, 500);
        }

        function animateFloorspaceElementsOut() {
            $('#floorspace .title').animate({
                bottom: -56
            }, 400);

            $('#floorspace .tile1').animate({
                bottom: -136
            }, 600);

            $('#floorspace .tile2').animate({
                bottom: -152
            }, 700);

            $('#floorspace .hero').animate({
                bottom: -464
            }, 1000, function () {
                $('#floorspace').hide();
            });

            $('#floorspace .content1').animate({
                bottom: -112
            }, 400);

            $('#floorspace .content2').animate({
                bottom: -104
            }, 500);
        }
    </script>
</head>
<body>
    <div id="vert-wrapper">
        <div id="wrapper">
            <aside id="sidebar">
                <nav id="navigation">
                    <ul>
                        <li><a href="#">Building</a></li>
                        <li><a href="#reception">Reception</a></li>
                        <li><a href="#floorspace">Floor Space</a></li>
                        <li><a href="#">Views</a></li>
                        <li><a href="#">Terraces</a></li>
                        <li><a href="#">Profile</a></li>
                    </ul>
                    <ul>
                        <li><a href="#">Specification</a></li>
                        <li><a href="#">Plans</a></li>
                        <li><a href="#">Location</a></li>
                        <li><a href="#">Ten Storeys</a></li>
                        <li><a href="#">Gallery</a></li>
                        <li><a href="#">Contact</a></li>
                    </ul>
                </nav>
            </aside>  
            <div id="content">
                <article id="reception">
                    <h1 class="title">
                        <img src="/images/reception/title.png" alt="Edge" />
                    </h1>
                    <img src="/images/reception/1.jpg" alt="" class="tile1" />
                    <img src="/images/reception/2.jpg" alt="" class="tile2" />
                    <img src="/images/reception/hero.jpg" alt="" class="hero" />
                    <img src="/images/reception/content1.jpg" alt="" class="content1" />
                    <img src="/images/reception/content2.jpg" alt="" class="content2" />
                </article>
                <article id="floorspace">
                    <h1 class="title">
                        <img src="/images/floorspace/title.png" alt="Space" />
                    </h1>
                    <img src="/images/floorspace/1.jpg" alt="" class="tile1" />
                    <img src="/images/floorspace/2.jpg" alt="" class="tile2" />
                    <img src="/images/floorspace/hero.jpg" alt="" class="hero" />
                    <img src="/images/floorspace/content1.jpg" alt="" class="content1" />
                    <img src="/images/floorspace/content2.jpg" alt="" class="content2" />
                </article>
            </div>          
        </div>
    </div>
</body>

现在我上面的代码确实可以工作,但我觉得它不够简洁,也似乎不能100%正确执行。 基本上我遇到的问题是,我希望能够在animateContentOut()完成后执行animateContentIn()。我唯一成功的方法是延迟animateContentIn()函数所需的时间,即1000毫秒,这是最长动画所需的时间。 有没有更整洁、更高效的方法来编写这个?

分享 executeMyAnimationFunction 函数内的代码。 - Arun P Johny
3
请为你的 executeMyAnimationFunction 函数添加一个回调函数。 - j08691
1
为什么不使用动画本身的回调函数? - bipen
jQuery 中的大多数动画函数都有一个 complete 参数,您可以通过它传递一个回调函数,在动画完成时调用该函数。 - Brian Rogers
3个回答

4
function someRandomFunction(){
    // This will be executed after myFirstFunction
}

function myFirstFunction(callbackFunction){
    // Do some stuff
    alert(1);
    // Do something slow here

    // Callback when done:
    callbackFunction(some, input);
}
// Usage:
myFirstFunction( someRandomFunction ); // with existing function
myFirstFunction( function(){ alert(1);} ); // anonymous

注意:您可以使用匿名函数
小示例:http://jsfiddle.net/zcp82/2/

另一个包含好信息的话题:在JavaScript中创建自定义回调函数


2

需要使用回调函数吗?

function executeMyAnimationFunction(complete){
    $('div').animate({ height: '1px' }, 500, complete);
}

这样调用:

executeMyAnimationFunction(function(){
    console.log('animation complete');
});

如果您坚持使用 Promise:

executeMyAnimationFunction(){
    var dfd = $.deferred();

    $('div').animate({ height: '1px' }, 500, function(){
        dfd.resolve();
    });

    return dfd.promise();
}

executeMyAnimationFunction().done(function(){
    console.log('animation complete');
});

0
请参考旧文章
这似乎是重复的问题,如果您调用多个函数,它们将按顺序依次调用。

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