Created
August 27, 2012 11:48
-
-
Save jerone/3487795 to your computer and use it in GitHub Desktop.
jQuery Ping domain/ip with Deferred
This file contains hidden or 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
/* | |
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(); | |
} | |
}); |
This file contains hidden or 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
/* 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); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is not working when I send ping request to 8.8.8.8 IP address.