Desired to have a JavaScript to loop trough a specific URL to find existing images using number incrementation ("https://6od.hu/data/hej_Page_%D.png"
, where %D
is incremented).
Trying to Check if image exists without loading it and using the while
loop:
The working code
function imageExists(url) {
return new Promise((resolve, reject) => {
const img = new Image(url);
img.onerror = reject;
img.onload = resolve;
const timer = setInterval(() => {
if (img.naturalWidth && img.naturalHeight) {
img.src = ''; /* stop loading */
clearInterval(timer);
resolve();
}
}, 10);
img.src = url;
});
}
function loadImg(i) {
const src_pattern = "https://6od.hu/data/hej_Page_0%D.png"
let src = src_pattern.replace("%D", i);
imageExists(src)
.then(() => console.log("Image exists."))
.catch(() => console.log("Image not exists."));
}
console.log(loadImg(5)); // true|false needed to return here
How this Promise object can return true
/false
for the loop?
I am just learning these Promise objects, please try to be descriptive. Thank you.
Desired loop
let i = 1;
while (loadImg(i)) {
console.log(i + ": " + loadImg(i)); // log all of the existing img than stop
i++;
}