Skip to content

Instantly share code, notes, and snippets.

@chrisdavidmiles
Created September 11, 2018 02:14
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 chrisdavidmiles/a07326e440dd5fb909f5bd26e9cb0555 to your computer and use it in GitHub Desktop.
Save chrisdavidmiles/a07326e440dd5fb909f5bd26e9cb0555 to your computer and use it in GitHub Desktop.
/**
* Creates a Ping instance.
* @returns {Ping}
* @constructor
*/
var Ping = function() {};
/**
* Pings source and triggers a callback when completed.
* @param source Source of the website or server, including protocol and port.
* @param callback Callback function to trigger when completed.
* @param timeout Optional number of milliseconds to wait before aborting.
*/
Ping.prototype.ping = function(source, callback, timeout) {
this.img = new Image();
timeout = timeout || 0;
var timer;
var start = new Date();
this.img.onload = this.img.onerror = pingCheck;
if (timeout) { timer = setTimeout(pingCheck, timeout); }
/**
* Times ping and triggers callback.
*/
function pingCheck() {
if (timer) { clearTimeout(timer); }
var pong = new Date() - start;
if (typeof callback === "function") {
callback(pong);
}else{
console.log('error');
}
}
this.img.src = source + "/?" + (+new Date()); // Trigger image load with cache buster
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment