2010-09-20 57 views
2

這是我到目前爲止。我想爲功能spid()設置超時。如何設置此jQuery代碼的超時時間?

<script type="text/javascript"> 

$(document).ready(function() { 
    $("#spid").animate({top: '-110px' }, 600, 'easeOutBounce', 
    function spid() { 
     $(this).animate({top:"-=20px"},1000).animate({top:"+=20px"},1000); 
     setTimeout("spid()",2000); 
    }); 
}); 
+0

爲' setInterval'&'setTimeout',請不要傳遞參數作爲字符串。雖然這是正確的方式,但耗時'因爲字符串再次需要解析 – 2010-09-20 16:41:55

+0

你能給我一個例子 – Noob 2010-09-20 16:42:31

+0

這不需要一個例子來解釋,我猜你可以想起它 – 2010-09-20 16:49:20

回答

0
$(function() { 
    $("#spid").animate({top: '190px' }, 600,'linear' ,function() { 
     (function spid() { 
      console.log('Test'); 
      $(this).animate({top:"+=20px"},1000).animate({top:"+=20px"},1000); 
      setTimeout(spid,2000); 
     })(); 
    }); 
}); 

有在上面的代碼與this一個問題,下面的代碼片段工作正常

編輯

$(function() { 
    $("#spid").animate({top: '110px' }, 600,'linear' ,function() { 
    var cache = $(this); 
    (function spid() { 
     cache.animate({top:"+=20px"},1000).animate({top:"-=20px"},1000); 
     setTimeout(spid,2000); 
    })(); 
    }); 
}); 

請測試代碼http://jsbin.com/elaxa3

+0

它顯示測試,測試,測試 – Noob 2010-09-20 17:06:52

+0

是的,這意味着代碼工作正常。是不是=) – 2010-09-20 17:14:24

+0

是的,它的作品,但它劑量動畫 – Noob 2010-09-20 17:15:48

0

你只需要傳遞一個函數。

setTimeout(spid,2000); 

或者你也可以使用setInterval