-
-
Save chrisdavidmiles/a07326e440dd5fb909f5bd26e9cb0555 to your computer and use it in GitHub Desktop.
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
/** | |
* 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