javascript - 在循环中对 setTimeout 延迟应用缓动

标签 javascript

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

我完全不知道如何开始。

希望有人能提供帮助。

最佳答案

这听起来像是 Robert Penner 的缓和方程式的工作!您可以下载原始的 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);
}

关于javascript - 在循环中对 setTimeout 延迟应用缓动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12081547/

相关文章:

javascript - event.preventDefault() 在 .then 内部不起作用

javascript - 如何将 json 文件导入 AngularJs 应用程序?

javascript - 我们可以在 react-data-grid 中使某些行不可编辑吗?

javascript - 简单的左右滚动选取框

javascript - 通过将指定的 el 传递到 subview 实例化中,将 View 渲染到父 div 中

javascript - 如何使用 react-native-fbsdk 提供的 LoginManager 从 facebook 注销?

javascript - 使用 Papa Parse 框架将 CSV 文件转换为 JSON 时如何处理 "undefined"错误?

javascript - 调用多个 Google Cloud Run 请求是否会调用容器的新实例

javascript - Firebase 实时数据库值事件期间传输的数据

javascript - 基于 JavaScript/jQuery 中的数据属性值隐藏/显示 div