Skip to content

Instantly share code, notes, and snippets.

@JLChnToZ
Created November 9, 2014 04:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JLChnToZ/72180433c7bfebdbf89d to your computer and use it in GitHub Desktop.
Save JLChnToZ/72180433c7bfebdbf89d to your computer and use it in GitHub Desktop.
Auto Adjust Timer Function, does not 100% guarantee accurate.
(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