JSFiddle - React, Tailwind, and code Playground
CSS
.success {
color: green;
}
.error, .timeout {
color: red;
}
JavaScript
function testImage(url, onSuccessCallback, onErrorCallback, timeout) {
timeout = timeout || 5000;
var timedOut = false, timer;
var img = new Image();
img.onerror = img.onabort = function() {
if (!timedOut) {
clearTimeout(timer);
onErrorCallback();
}
};
img.onload = function() {
if (!timedOut) {
clearTimeout(timer);
onSuccessCallback(url, "success");
}
};
img.src = url;
timer = setTimeout(function() {
timedOut = true;
onErrorCallback();
}, timeout);
}
function record(url, result) {
document.body.innerHTML += "<span class='" + result + "'>" +
result + ": " + url + "</span><br>";
}
const lienWebCam = "http://www.cnn.com/foo.jpg"
const lienArchive = "http://photos.smugmug.com/photos/invalid344291068_HdnTo-Ti.jpg"
const lienError = "http://photos.smugmug.com/photos/344291068_HdnTo-Ti.jpg"
const checkImages = () => {
testImage(lienWebCam, record, () => {
testImage(lienArchive, record, () => {
testImage(lienError, record, () => {
//Aucunes des 3 images n'est chargable
})
})
})
}
//Appel la fonction checkImages toutes les secondes
setInterval(checkImages, 1000)