Skip to content

Instantly share code, notes, and snippets.

@hmschreiner
Created January 5, 2016 15:18
Show Gist options
  • Save hmschreiner/81047ca6a794fea8ccc7 to your computer and use it in GitHub Desktop.
Save hmschreiner/81047ca6a794fea8ccc7 to your computer and use it in GitHub Desktop.
Just an "implementation" of ping function used on terminal with javascript using Promise.
var Ping = (function(){
function Ping (url, pings){
this.url = url;
this.pings = pings || 3;
this.totalPings = 0;
this.totalSuccess = 0;
this.totalError = 0;
this.time = 0;
this.interval = null;
return this;
};
Ping.prototype.setInterval = function (interval){
this.interval = interval;
};
Ping.prototype.createRandomCache = function (){
return Math.floor((1 + Math.random()) * 0x10000).toString(16);
};
Ping.prototype.getBaseURL = function (url){
var pathArray = this.url.split( '/' ),
protocol = pathArray[0],
host = pathArray[2];
return protocol + '//' + host;
}
Ping.prototype.requestImage = function () {
var _self = this;
return new Promise(function(resolve, reject) {
var img = new Image();
img.onload = function() {
resolve(img);
};
img.onerror = function() {
reject(_self.url);
};
img.src = _self.url + '?random-no-cache=' + _self.createRandomCache();
});
};
Ping.prototype.execute = function (multiplier) {
var _self = this;
if (_self.interval === null) {
_self.messageLog('PING ' + _self.getBaseURL());
_self.interval = setInterval(function () {
_self.execute(multiplier);
}, 1000);
}
if (_self.totalPings >= _self.pings) {
clearInterval(_self.interval);
_self.messageLog('Done. <br><br>');
_self.messageLog('Results:');
_self.messageLog('--- Succeed: ' + _self.totalSuccess);
_self.messageLog('--- Failed: ' + _self.totalError);
_self.messageLog('--- Time: ' + _self.time + 'ms');
return;
}
new Promise(function(resolve, reject) {
var start = (new Date()).getTime(),
response = function() {
var delta = ((new Date()).getTime() - start);
delta *= (multiplier || 1);
resolve(delta);
};
_self.requestImage()
.then(response)
.catch(reject);
// Set a timeout for max-pings, 5s.
setTimeout(function() {
reject(Error('Timeout'));
}, 5000);
})
.then(function(delta) {
_self.time += delta;
_self.messageLog('Ping delay: ' + delta + 'ms');
_self.totalSuccess++;
})
.catch(function(error){
_self.messageLog('Failed to load resource.');
_self.totalError++;
});
_self.totalPings++;
};
Ping.prototype.messageLog = function (logMessage, appendToDocument){
if (appendToDocument === undefined) {
console.log(logMessage);
return;
}
var logContainer = document.createElement('div');
logContainer.innerHTML = logMessage;
document.body.appendChild(logContainer);
}
return Ping;
})();
var Ping = new Ping('https://www.google.com.br/images/nav_logo242.png');
Ping.execute();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment