Currently, I am creating a system to show random pictures every 0.5 seconds. I have almost 40k pictures +-
But, I am getting issues to load these pictures using Javascript.
1 - If I load them too fast, I got sometimes "cancelled" as response in console. (https://prnt.sc/1t23k2o)
2 - If I check if the image was successfully loaded to load the next image, I get an delay and this result in bottleneck showing images every 0.5 seconds. (onLoad)
(function getImages(i) {
setTimeout(function() {
v++;
var r = Math.random();
img.src = "seg/out-" + v + ".jpg?v=" + r;
if (--i) getImages(i);
}, 500)
})(300); // trigger this function 300x
How do I handle this? Could you help me improve my logic? Thank you.
You can try pre-load an image at the end of the previous timeout, like that:
function preLoadImage(src) {
const preloader = new Image();
preloader.src = src;
}
function setImage(src) {
img.src = src;
}
(function getImages(i, currentSrc) {
setTimeout(function() {
v++;
setImage(currentSrc);
const r = Math.random();
const nextSrc = "seg/out-" + v + ".jpg?v=" + r;
preLoadImage(nextSrc);
if (--i) getImages(i, nextSrc);
}, 500)
})(300);
Let me know if it works for you or not.