我在javascript循环中调用多个setTimeout。目前,每次迭代时延迟增加200ms,使'self.turnpages()'函数每200ms触发一次。
但是我想对这些可变延迟应用某种缓动,以便当循环开始到达最后几次迭代时,延迟进一步分开,导致函数触发减慢。
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);
}
我完全不知道如何从这开始。
希望有人可以提供帮助。
答案 0 :(得分:10)
这听起来像罗伯特·彭纳的缓和方程式!您可以下载原始的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);
}
答案 1 :(得分:0)
2019年答案:您无需自行编写循环定时或处理单个字符变量,只需轻松地运行函数即可。这是一个使用npm中的easy-ease
的简单示例:
import ease from 'easy-ease';
ease({
startValue: 1,
endValue: 33,
durationMs: 2000,
onStep: function(value) {
console.log(value)
}
});