Skip to content

Instantly share code, notes, and snippets.

@Aleksey-Danchin
Created May 31, 2015 22:13
Show Gist options
  • Save Aleksey-Danchin/0b7db3a48f0da7f6076e to your computer and use it in GitHub Desktop.
Save Aleksey-Danchin/0b7db3a48f0da7f6076e to your computer and use it in GitHub Desktop.
setIntervalControlling
function setIntervalControlling (callback, time) {
var startMoment = (new Date).getTime(),
number = 0, timeOfLoop = 0, difference = 0,
realTime = time, minStep = Math.pow(2, -4);
var loop;
__restart();
return { stop: function () { clearInterval(loop); } };
function __restart () {
clearInterval(loop);
callback();
if (difference !== 0) {
time += minStep * (difference > 0 ? -1 : 1);
startMoment = (new Date).getTime();
number = 0;
}
loop = setInterval(function () {
number++;
timeOfLoop = (new Date).getTime() - startMoment;
difference = timeOfLoop - number * realTime;
if (Math.abs(difference) >= realTime) __restart();
else callback();
}, time);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment