Skip to content

Instantly share code, notes, and snippets.

@betamos
Created August 25, 2013 23:25
Show Gist options
  • Save betamos/6336944 to your computer and use it in GitHub Desktop.
Save betamos/6336944 to your computer and use it in GitHub Desktop.
Playing around with more accurate JS timeouts for long durations with system time as reference
/**
* Long timeouts that remain accuracy.
*/
// When the final system adjusted timer kicks in
var FINAL_COUNTDOWN = 2000;
var accurate = {};
accurate.setTimeout = function(fn, t) {
var begin = new Date().getTime();
var end = begin + t;
setTimeout(function() {
// Measure again properly
var now = new Date().getTime();
setTimeout(fn, end - now);
}, t - FINAL_COUNTDOWN);
}
accurate.testTimeout = function(t) {
var d = new Date();
console.log('Beginning timeout test at '+ d);
var begin = d.getTime();
var end = begin + t;
setTimeout(function() {
var now = new Date().getTime();
console.log('setTimeout error: '+ (now - end));
}, t);
accurate.setTimeout(function() {
var now = new Date().getTime();
console.log('accurate.setTimeout error: '+ (now - end));
}, t);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment