Last active
April 3, 2017 18:48
-
-
Save bjouhier/c7adb5f54caf9fc86d6e to your computer and use it in GitHub Desktop.
timedrift.js
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
"use strict"; | |
function millis(hr) { | |
return hr[0] * 1000 + Math.floor(hr[1] / 1000000); | |
} | |
function busyWait(ms, cb) { | |
var hr0 = process.hrtime(); | |
while (millis(process.hrtime(hr0)) < ms); | |
var elapsed = millis(process.hrtime(hr0)); | |
console.log("busy:\texpected " + ms + ", got " + elapsed); | |
cb(); | |
} | |
function idleWait(ms, cb) { | |
var hr0 = process.hrtime(); | |
setTimeout(function() { | |
var elapsed = millis(process.hrtime(hr0)); | |
console.log("idle:\texpected " + ms + ", got " + elapsed + // | |
(elapsed > ms + 100 ? " SURPRISE!!" : "")); | |
cb(); | |
}, ms); | |
} | |
function combined(a) { | |
busyWait(300, function() { | |
idleWait(100,function(){ | |
a < 50 && combined(++a); | |
}); | |
}); | |
} | |
combined(0); |
I update to measure times with process.hrtime
rather than Date.now
. Same results
the fact that you get a drift exactly equal to the amount of time you sleep/idle looks suspiciously like the error i get using chained setTimeout()'s. if you want to read my gist, you'll see somehow using clearTimeout() eradicates the drift. https://gist.github.com/natbro/bf872ac473a1bba04008
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: