9

我在 javascript 循环中调用多个 setTimeout。当前将延迟设置为在每次迭代时增加 200 毫秒,使“self.turnpages()”函数每 200 毫秒触发一次。

但是,我想对这些可变延迟应用某种缓和,以便当循环开始到达最后几次迭代时,延迟会进一步分开,从而导致函数触发减慢。

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);
}

我完全不知道如何从这个开始。

希望有人可以提供帮助。

4

2 回答 2

10

这听起来像是 Robert Penner 的缓动方程的工作!您可以在此处下载原始的 ActionScript 2.0 版本(只需删除参数上的强类型以移植到 JavaScript),此处对参数有很好的解释。

像下面这样的东西会做你想要的(小提琴):

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);
}
于 2012-08-22T22:10:15.537 回答
4

2019 年回答:您不需要制作自己的循环计时,或处理单个字符变量,只需使用缓动运行函数即可。easy-ease这是一个使用npm的快速示例:


import ease from 'easy-ease';

ease({
  startValue: 1,
  endValue: 33,
  durationMs: 2000,
  onStep: function(value) {
    console.log(value)
  }
});
于 2019-10-23T11:54:18.700 回答