JS代码运行速度很慢

nat*_*684 0 html javascript css jquery

我是一个JS新手,所以在这里轻松我.但我写了一个简单的幻灯片,它似乎运行得很慢.以下代码在我自己的机器上本地加载大约需要2-4秒.想知道造成延误的原因.让我知道,谢谢!

function slideshow(){
    $("#1").animate({top: "50px",}, 500).delay(2000);
    $("#1").animate({top: "400px",}, 500);
    $("#2").animate({top: "50px",}, 500).delay(2000);
    $("#2").animate({top: "400px",}, 500);
    $("#3").animate({top: "50px",}, 500).delay(2000);
    $("#3").animate({top: "400px",}, 500);
    $("#4").animate({top: "50px",}, 500).delay(2000);
    $("#4").animate({top: "400px",}, 500);
    $("#5").animate({top: "50px",}, 500).delay(2000);
    $("#5").animate({top: "400px",}, 500);
    slideshow();
}
Run Code Online (Sandbox Code Playgroud)

每个ID代表不同的图像.

nnn*_*nnn 7

您的代码存在的一个问题,因为其他答案似乎都没有讨论过它,最后一行slideshow()调用本身是递归的,这会导致堆栈溢出.不要这样做:

function slideshow() {
   // animate code
   slideshow();
}
Run Code Online (Sandbox Code Playgroud)

相反,如果您希望它重复运行,请使用x毫秒后setTimeout()对该函数的另一次执行进行排队:

function slideshow() {
   // animate code
   setTimeout(slideshow, 3500);
}
Run Code Online (Sandbox Code Playgroud)

你拥有它的方式,实际上没有任何功能完成.使用时setTimeout(),每次调用都会slideshow()完成,然后在指定的延迟后运行一个单独的调用.我会使延迟足够大,以便在当前动画完成后进行下一次调用,否则您将比运行更快地排队越来越多的动画.

更新: jQuery为每个元素维护单独的动画队列,这意味着五个元素上的动画将同时运行.其他一些答案已经提供了一次一个地按顺序运行动画的方法,但这是我如何做到的:

$(window).on("load",function() {    
    // cache a jQuery object containing the elements to animate
    // (note you don't need their ids if you use their class)
    var $imgs = $('img.slideshow-image'),
        i = 0;

    function slideShow() {
       // start animation for "current" img
       $imgs.eq(i).show(1)
                  .animate({top: "50px",}, 500)
                  .delay(2000)
                  .animate({top: "400px",}, 500)
                  .hide(1, function() {
                     i = (i+1) % $imgs.length;
                     setTimeout(slideShow, 500);
                  });
    }    
    slideShow();    
});
Run Code Online (Sandbox Code Playgroud)

工作演示:http://jsfiddle.net/bARwb/

  • 我已将代码包装在一个加载处理程序中,以消除对内联onload=属性的需要,并将代码保留在全局范围之外(如果这样做,请不要忘记onload="slideShow()"从body标签中删除).
  • 我添加.show().hide()电话(的持续时间,使他们加入到动画队列),使得IMG元素将display:none在动画之间,否则你的position:relative风格,你看不到任何但是第一(但改变以position:absolute将阻止他们获得由他们的父母裁剪overflow:hidden).
  • 当动画完成一个元素时,从.hide()增量的回调i引用下一个元素的索引(但检查它何时经过最后一个元素)然后用于setTimeout()为下一个元素排队动画.