在循环内将缓动应用于setTimeout延迟 [英] Applying easing to setTimeout delays, within a loop

查看:64
本文介绍了在循环内将缓动应用于setTimeout延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am calling multiple setTimeout's within a javascript loop. The delay is currently set to increase by 200ms upon every iteration making the 'self.turnpages()' function fire every 200ms.

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

However I would like to apply some sort of easing to these variable delays so that as the loop begins to reach the last few iterations the delay gets further apart causing the function firing to slow down.

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

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

I am at a complete loss how to start with this.

希望有人可以提供帮助。

Hopefully someone can help.

推荐答案

这听起来像罗伯特·彭纳的宽松工作方程!您可以下载原始的ActionScript 2.0版本此处(只需删除对端口参数的强类型到JavaScript)并且这里的参数有很好的解释。

This sounds like a job for Robert Penner's easing equations! You can download the original ActionScript 2.0 versions here (just remove the strong-typing on the parameters to port to JavaScript) and there's a good explanation of the parameters here.

以下内容将满足您的需求(小提琴):

Something like the following will do what you want (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);
}

这篇关于在循环内将缓动应用于setTimeout延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆