Skip to content

Instantly share code, notes, and snippets.

@0xa
Created November 19, 2015 00:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0xa/a94a5abbe19b4ea93f4f to your computer and use it in GitHub Desktop.
Save 0xa/a94a5abbe19b4ea93f4f to your computer and use it in GitHub Desktop.
Resource Timing API JavaScript ping
function perf_ping(host, callback, start) {
if (start == undefined) {
var perfEntries = performance.getEntries();
// use the last perf entry to ignore any request preceding
// this ping() call
start = 0;
for (var i = 0; i < perfEntries.length; i++) {
if (start < perfEntries[i].startTime) {
start = perfEntries[i].startTime;
}
}
console.log("start: " + start);
}
var timer = setTimeout(function() {
callback('timeout');
}, TIMEOUT);
var url = 'http://' + host + '/ping';
var random_thing = "?" + String(Math.random()).slice(2)
function ok() {
clearTimeout(timer);
var average = 0;
var count = 0;
var perfEntries = performance.getEntries();
for (var i = 0; i < perfEntries.length; i++) {
var e = perfEntries[i];
// ignore old entries
if (e.startTime < start) {
continue;
}
// ignore other stuff
if (e.name.slice(0, url.length) != url || e.entryType != 'resource') {
continue;
}
var time = e.duration - Math.max(e.requestStart - e.startTime, 0);
average = (average*count + time) / (count+1);
count += 1;
}
if (count < NPINGS) {
ping(host, callback, count, start);
return;
}
average -= 2; // average difference to a simple icmp ping
callback(Math.round(average) + 'ms');
}
var img = new Image();
img.onload = ok;
img.onerror = ok;
img.src = url + random_thing;
callback('...');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment