|
1 | 1 | /*
|
2 |
| - * ping.js - v0.1.2 |
| 2 | + * ping.js - v0.1.3 |
3 | 3 | * Ping Utilities in Javascript
|
4 | 4 | * http://github.com/alfg/ping.js
|
5 | 5 | *
|
|
11 | 11 | * @returns {Ping}
|
12 | 12 | * @constructor
|
13 | 13 | */
|
14 |
| -var Ping = function() {}; |
| 14 | +var Ping = function(opt) { |
| 15 | + this.opt = opt || {}; |
| 16 | + this.favicon = this.opt.favicon || "/favicon.ico"; |
| 17 | + this.timeout = this.opt.timeout || 0; |
| 18 | +}; |
15 | 19 |
|
16 | 20 | /**
|
17 | 21 | * Pings source and triggers a callback when completed.
|
18 | 22 | * @param source Source of the website or server, including protocol and port.
|
19 |
| - * @param callback Callback function to trigger when completed. |
| 23 | + * @param callback Callback function to trigger when completed. Returns error and ping value. |
20 | 24 | * @param timeout Optional number of milliseconds to wait before aborting.
|
21 | 25 | */
|
22 |
| -Ping.prototype.ping = function(source, callback, timeout) { |
| 26 | +Ping.prototype.ping = function(source, callback) { |
23 | 27 | this.img = new Image();
|
24 |
| - timeout = timeout || 0; |
25 | 28 | var timer;
|
26 | 29 |
|
27 | 30 | var start = new Date();
|
28 | 31 | this.img.onload = pingCheck;
|
29 |
| - this.img.onerror = pingError; |
30 |
| - if (timeout) { timer = setTimeout(pingCheck, timeout); } |
| 32 | + this.img.onerror = pingCheck; |
| 33 | + if (this.timeout) { timer = setTimeout(pingCheck, this.timeout); } |
31 | 34 |
|
32 |
| - /** |
33 |
| - * Does not resolve. |
34 |
| - */ |
35 |
| - function pingError() { |
36 |
| - callback("Error"); |
37 |
| - } |
38 |
| - |
39 | 35 | /**
|
40 | 36 | * Times ping and triggers callback.
|
41 | 37 | */
|
42 |
| - function pingCheck() { |
| 38 | + function pingCheck(e) { |
43 | 39 | if (timer) { clearTimeout(timer); }
|
44 | 40 | var pong = new Date() - start;
|
45 | 41 |
|
46 | 42 | if (typeof callback === "function") {
|
47 |
| - callback(pong); |
| 43 | + if (e.type === "error") { |
| 44 | + console.error("error loading resource"); |
| 45 | + return callback("error", pong); |
| 46 | + } |
| 47 | + return callback(null, pong); |
48 | 48 | }
|
49 | 49 | }
|
50 | 50 |
|
51 |
| - this.img.src = source + "/favicon.ico?" + (+new Date()); // Trigger image load with cache buster |
| 51 | + this.img.src = source + this.favicon + "?" + (+new Date()); // Trigger image load with cache buster |
52 | 52 | };
|
0 commit comments