JSFiddle - React, Tailwind, and code Playground
HTML
<div id="container"></div>
CSS
.pending {
color: orange;
}
.success {
color: green;
}
.error {
color: red;
}
JavaScript
var Ping = function Ping(url, callback) {
var self = this;
if(!this.pending) {
this.pending = true;
this.url = url + "?nocache=" + new Date();
this.callback = callback;
this.img = new Image();
this.img.onload = function() {
if(self.pending) {
self.callback(true);
clearTimeout(self.timer);
self.pending = false;
}
}
this.img.onerror = function() {
if(self.pending) {
self.callback(true);
clearTimeout(self.timer);
self.pending = false;
}
}
this.timer = setTimeout(function() {
if(self.pending) {
self.callback(false);
self.pending = false;
}
}, 3000);
this.img.src = this.url;
}
}
var urls = [
"localhost",
"openclassrooms.com",
"tmtp://tm-tuta-serveur",
"sandhose.fr:1337" // Serveur qui met 10 secondes à répondre -> considéré comme down
];
var container = document.getElementById("container");
var e = [], p = [];
for(var i = 0; i < urls.length; i++) {
e[i] = document.createElement("div");
e[i].innerHTML = urls[i];
e[i].className = "pending";
p[i] = new Ping("http://" + urls[i], function(elem, success) {
elem.className = success ? "success" : "error";
}.bind(null, e[i]));
container.appendChild(e[i]);
}