Created
November 9, 2014 04:19
-
-
Save JLChnToZ/72180433c7bfebdbf89d to your computer and use it in GitHub Desktop.
Auto Adjust Timer Function, does not 100% guarantee accurate.
This file contains 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(root) { | |
if(!root) root = {}; | |
var nextID = 0, timers = []; | |
root.setAutoAdjustInterval = function(callback, interval, timeKeeperFunc, frameTheshold) { | |
if(!timeKeeperFunc || typeof timeKeeperFunc != "function") | |
timeKeeperFunc = Date.now; | |
if(!frameTheshold || typeof frameTheshold != "number") | |
frameTheshold = 1000 / interval; | |
var timeDiff, | |
thisTS, | |
startTS = timeKeeperFunc(), | |
lastTS = startTS, | |
thisID = nextID++, | |
times = 1, | |
timeDiffs = [], | |
calcInterval = interval, | |
fn = function() { | |
if(timers.indexOf(thisID) < 0) return; | |
thisTS = timeKeeperFunc(); | |
timeDiff = thisTS - startTS; | |
calcInterval = Math.round(interval * interval * times / timeDiff); | |
callback(); | |
setTimeout(fn, calcInterval); | |
timeDiffs.push(thisTS - lastTS); | |
lastTS = thisTS; | |
if(times < frameTheshold) times++; | |
else startTS += timeDiffs.shift(); | |
}; | |
setTimeout(fn, interval); | |
timers.push(thisID); | |
return thisID; | |
}; | |
root.clearAutoAdjustInterval = function(id) { | |
var index = timers.indexOf(id); | |
if(index >= 0) | |
timers.splice(index, 1); | |
}; | |
})(this); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment