2012-08-22 33 views
7

我在一個javascript循環中調用多個setTimeout。當每次迭代時,延遲目前設置爲增加200ms,使得'self.turnpages()'函數每200ms觸發一次。在一個循環內應用緩動setTimeout延遲

但是我想對這些可變延遲應用某種緩動,這樣當循環開始達到最後幾次迭代時,延遲會進一步分開,從而導致函數發射減慢。

var self = this;  
var time = 0; 

for(var i = hide, len = diff; i < len; i++) { 
        (function(s){ 
          setTimeout(function(){      
             self.turnPages(s);       
          }, time); 
         })(i);         
      time = (time+200); 
} 

我完全喪失瞭如何從這開始。

希望有人可以提供幫助。

+2

取而代之的200是一個常數,它應該是「我」的功能。 – Pointy

+0

@Pointy - 然而,的確,我不知道從哪裏開始實現我所需要的數學。 – gordyr

+1

那麼這取決於你想要的緩和曲線看起來像我猜。 – Pointy

回答

9

這聽起來像是羅伯特潘納鬆弛方程式的工作!您可以下載最初的ActionScript 2.0版本here(只需刪除參數上的強類型即可移植到JavaScript),並且可以很好地解釋參數here

像下面會做你想要什麼(fiddle):

var time = 0; 
var diff = 30; 

var minTime = 0; 
var maxTime = 1000; 

// http://upshots.org/actionscript/jsas-understanding-easing 
/* 
    @t is the current time (or position) of the tween. This can be seconds or frames, steps, seconds, ms, whatever – as long as the unit is the same as is used for the total time [3]. 
    @b is the beginning value of the property. 
    @c is the change between the beginning and destination value of the property. 
    @d is the total time of the tween. 
*/ 
function easeInOutQuad(t, b, c, d) { 
    if ((t /= d/2) < 1) return c/2 * t * t + b; 
    return -c/2 * ((--t) * (t - 2) - 1) + b; 
} 

function easeOutQuad(t, b, c, d) { 
    return -c * (t /= d) * (t - 2) + b; 
} 

function easeInQuad(t, b, c, d) { 
    return c * (t /= d) * t + b; 
} 

for (var i = 0, len = diff; i <= len; i++) { 
    (function(s) { 
    setTimeout(function() { 
     //self.turnPages(s);       
     console.log("Page " + s + " turned"); 
    }, time); 
    })(i); 

    time = easeInOutQuad(i, minTime, maxTime, diff); 
    console.log(time); 
} 
+0

絕對完美。謝謝 – gordyr

+0

沒問題gordyr,愉快的寬鬆! –