2012-08-22 34 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,愉快的宽松! –