Created
August 25, 2013 23:25
-
-
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
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
/** | |
* 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