Created
November 11, 2013 06:55
-
-
Save dannycoates/7409011 to your computer and use it in GitHub Desktop.
js version of toobusy
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
var interval = 500 | |
var maxLag = 70 | |
var lag = 0 | |
var decay = 3 | |
var mark = [] | |
var timer = null | |
function tooslow() { | |
return (lag > maxLag) && | |
Math.random() < ((lag - maxLag) / maxLag) | |
} | |
tooslow.lag = function () { return lag } | |
tooslow.maxLag = function (x) { | |
if (x > 9) { | |
maxLag = x | |
} | |
return maxLag | |
} | |
tooslow.shutdown = function () { | |
clearTimeout(timer) | |
} | |
function ping() { | |
mark = process.hrtime() | |
setImmediate(pong) | |
} | |
function pong() { | |
var delta = process.hrtime(mark) | |
var delay = (delta[0] * 1e9 + delta[1]) / 1e6 | |
lag = Math.floor( | |
(delay + (lag * (decay - 1))) / decay | |
) | |
timer = setTimeout(ping, interval) | |
} | |
ping() | |
module.exports = tooslow |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment