Created
May 31, 2015 22:13
-
-
Save Aleksey-Danchin/0b7db3a48f0da7f6076e to your computer and use it in GitHub Desktop.
setIntervalControlling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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