Skip to content

Instantly share code, notes, and snippets.

@pherris

pherris/index.html

Last active Aug 29, 2015
Embed
What would you like to do?
Continual monitoring of JS latency on the client
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<script>
//add logging for client latency (when detected).
//to create client latency, Rally.metrics.wait(250);
document.addEventListener('clientLatency', function (evt) {
console.log('latency!', evt.detail);
}, false);
var Metrics = function () {
var intervalDelay = 200,
acceptableVariance = 10,
poller,
requested;
//helper to provide more precise timing if available
function getTs(useDateTS) {
return window.performance && !useDateTS ? window.performance.now() : new Date().getTime();
}
//tracks how long from when the 'event' was scheduled until it actually ran
function tracker() {
var now = getTs(), latency = now - requested - intervalDelay;
if (latency > acceptableVariance) {
var event = new CustomEvent('clientLatency', { 'detail': latency });
document.dispatchEvent(event);
}
//schedule this method to be invoked again
poller = setTimeout(tracker, intervalDelay);
//time this track 'event' was scheduled
requested = now;
}
function filterInt(value) {
if(/^(\-|\+)?([0-9]+|Infinity)$/.test(value))
return Number(value);
return NaN;
}
return {
cancel: function () {
if (poller) {
clearInterval(poller);
poller = null;
}
},
track: function () {
if (!poller) {
//first time executing
requested = getTs();
poller = setTimeout(tracker, intervalDelay);
return true;
}
return false;
},
/**
* Takes a ms param and waits for that many ms - reported latency will be
* wait time minus *no more than* intervalDelay. If you want guaranteed latency
* you need to request at least intervalDelay + acceptableVariance.
*/
wait: function (ms) {
if (isNaN(filterInt(ms))) {
return NaN;
}
var startWaiting = getTs();
while (getTs() < startWaiting + ms) {
//blocking
}
var doneWaiting = getTs();
return 'watied ' + (doneWaiting - startWaiting) + ', est total latency: ' + (requested + intervalDelay - doneWaiting);
}
};
}, Rally = {};
Rally.metrics = new Metrics();
Rally.metrics.track();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment