2013-05-09 202 views
0

我有一些简单地放大和缩小横幅图像的Jquery。当我运行这个时,浏览器中出现堆栈限制错误。它仍然运行,但是有没有办法让它只能“及时”加载到堆栈中?在查看堆栈时,它会在初始加载中一遍又一遍地加载zoomIn()zoomOut(),直到达到极限,因此页面加载非常缓慢。Jquery Animate无限循环:如何避免堆栈限制

$(document).ready(function(){ 

    $bannerImg = $('.post-picture img') 

    function zoomIn(){ 
     $bannerImg.animate({ 
      width: 1500, 
     }, 50000,'linear'); 

     $bannerImg.promise().done(zoomOut()); 
    } 

    function zoomOut(){ 
     $bannerImg.animate({ 
      width: 1500, 
     }, 50000,'linear'); 

     $bannerImg.promise().done(zoomIn()); 
    } 

    zoomIn(); 

}); 

更新:感谢您的答案。使用完成(ZoomOut/ZoomIn)工作。

回答

4

.done()期望的功能参考 - 功能通将尽快PROMI执行se对象被解析。相反,你只是调用函数(不管什么都不返回,undefined,反正)。如果你这样做,这些功能将不断地相互呼叫,作为一个无限循环。使用此:

$bannerImg.promise().done(zoomOut); 
// and later: 
$bannerImg.promise().done(zoomIn); 

DEMO:http://jsfiddle.net/G6uWs/

(我不得不改变号码,使其可用)

参考:

+1

非常感谢伊恩 – Brandonmchu 2013-05-09 19:30:17

4

您正在调用.done()中的函数,而不是将其作为参数传递。

$bannerImg.promise().done(zoomOut()); 

应该是

$bannerImg.promise().done(zoomOut); 

$bannerImg.promise().done(zoomIn()); 

应该是

$bannerImg.promise().done(zoomIn); 
0

看起来你正在造成无限循环。幸运的是,jQuery有一个完整的回调函数,可以用来防止无限循环。在

不间断放大和缩小的旗帜

$(document).ready(function() { 

    $bannerImg = $('.post-picture img'); 

    function zoomIn() { 
     $bannerImg.animate({ 
      width: 1500 
     }, { 
      duration: 10000, 
      complete: function() { 
       zoomOut(); 
      } 
     }); 
    } 

    function zoomOut() { 
     $bannerImg.animate({ 
      width: 100 
     }, { 
      duration: 10000, 
      complete: function() { 
       zoomIn(); 
      } 
     }); 
    } 

    zoomIn(); 

}); 

* 来源:*jsfiddle