我在 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/