Apply attenuation to setTimeout delays in a loop

I call multiple setTimeout in a javascript loop. The delay is currently set to 200 ms at each iteration, with the function "self.turnpages ()" triggered every 200 ms.

However, I would like to apply some kind of relief to these variable delays, so that as the loop begins to reach the last few iterations, the delay becomes even more detached, which slows down the function.

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 have a complete loss, how to start from this.

Hope someone can help.

+7
source share
1 answer

It sounds like a job for Robert Penner's equations! You can download the original versions of ActionScript 2.0 here (just remove the strong typing of parameters for the port in JavaScript), and there is 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); } 
+9
source

All Articles