JSFiddle - React, Tailwind, and code Playground
CSS
.success {
color: green;
}
.error, .timeout {
color: red;
}
JavaScript
function testImage(url, timeout) {
return new Promise((resolve) => {
timeout = timeout || 5000;
var timedOut = false, timer;
var img = new Image();
img.onerror = img.onabort = function() {
if (!timedOut) {
clearTimeout(timer);
resolve(false);
}
};
img.onload = function() {
if (!timedOut) {
clearTimeout(timer);
resolve(url)
}
};
img.src = url;
timer = setTimeout(function() {
timedOut = true;
resolve(false)
}, timeout);
})
}
function record(url, result) {
document.body.innerHTML += "<span class='" + result + "'>" +
result + ": " + url + "</span><br>";
}
(async() => {
let images = [
"http://www.cnn.com/foo.jpg",
"http://photos.smugmug.com/photos/invalid344291068_HdnTo-Ti.jpg",
"http://photos.smugmug.com/photos/344291068_HdnTo-Ti.jpg",
"https://www.google.com/images/srpr/logo3w.png"
]
for await( let img of images ) {
let image = await testImage( img )
if( image ) {
record(image, "success");
break;
}
else {
record(img, "error")
}
}
})();