首页 > 解决方案 > 递归调用java script animate函数,每次循环后时间处理

问题描述

在准备好的函数scrollDown动画开始,在scrollDown的完整回调监听器中我调用scrollUp函数开始向上滚动动画。循环完成后,向下滚动动画需要一些时间才能重新开始。更重要的是,每个周期完成后延迟时间都会增加。

$(document).ready(function(){
   scrollDown();
});
function scrollDown(){
    $('html, body').animate({
        scrollTop:$("#4").offset().top-100
    },
    {
        duration:2000,
        complete: function(){
           scrollUp();
        }
    });
}
function scrollUp(){
        $('html, body').animate({
            scrollTop:$("#1").offset().top-100
        },
        {
            duration:2000,
            complete: function(){
               scrollDown();
            }
        });
}

标签: javascriptanimationjquery-animate

解决方案


添加$('html, body').stop(); 成功了,现在动画很流畅,没有延迟时间。但是为什么我必须调用他的 stop() 函数呢?因为我已经实现了完整的回调。

$(document).ready(function(){
   scrollDown();
});
function scrollDown(){
    $('html, body').stop(); // no idea why I need to call this stop function
    $('html, body').animate({
        scrollTop:$("#4").offset().top-100
    },
    {
        duration:2000,
        complete: function(){
           scrollUp();
        }
    });
}
function scrollUp(){
        $('html, body').stop(); // no idea why I need to call this stop function
        $('html, body').animate({
            scrollTop:$("#1").offset().top-100
        },
        {
            duration:2000,
            complete: function(){
               scrollDown();
            }
        });
}

推荐阅读