Skip to content

Instantly share code, notes, and snippets.

@jerone
Created August 27, 2012 11:48
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jerone/3487795 to your computer and use it in GitHub Desktop.
Save jerone/3487795 to your computer and use it in GitHub Desktop.
jQuery Ping domain/ip with Deferred
/*
Ping
*/
$.extend($, {
Ping: function Ping(url, timeout) {
timeout = timeout || 1500;
var timer = null;
return $.Deferred(function deferred(defer) {
var img = new Image();
img.onload = function () { success("onload"); };
img.onerror = function () { success("onerror"); }; // onerror is also success, because this means the domain/ip is found, only the image not;
var start = new Date();
img.src = url += ("?cache=" + +start);
timer = window.setTimeout(function timer() { fail(); }, timeout);
function cleanup() {
window.clearTimeout(timer);
timer = img = null;
}
function success(on) {
cleanup();
defer.resolve(true, url, new Date() - start, on);
}
function fail() {
cleanup();
defer.reject(false, url, new Date() - start, "timeout");
}
}).promise();
}
});
/* example */
$.Ping("http://google.com" /*, optional timeout */).done(function (success, url, time, on) {
console.log("ping done", arguments);
}).fail(function (failure, url, time, on) {
console.log("ping fail", arguments);
});
@Dylan-chunshen
Copy link

Thank you for your work!

@arabinda-g
Copy link

This is not working when I send ping request to 8.8.8.8 IP address.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment