It seems like your goal is to rotate images indefinitely, but your current method is quite inefficient. Running 1000 timers simultaneously and loading all 1000 images at once is not the best approach.
Instead, a simpler solution using a modulo operator on the index and a basic function to update gallery images can be implemented.
Here is a minimalistic HTML structure for the gallery:
<div id="gallery">
<img id="gallery_a" onload="galleryLoaded()" />
<img id="gallery_b" onload="galleryLoaded()" />
</div>
The `onload` events are utilized to switch the visible image once loaded and to ensure smooth transitions.
An example showcasing this approach can be found here on JSFiddle.
No special CSS is required except for setting up the transition effect for the second image:
#gallery_b {
opacity: 0;
transition: opacity 1s;
}
A function periodically called will update the image index and toggle between the two images:
// This function initializes the image switch
function galleryNext() {
if (gallery_switching)
return;
gallery_switching = true;
gallery_index = (gallery_index + 1) % images.length;
document.getElementById(gallery_second ? 'gallery_a' : 'gallery_b').src = images[gallery_index];
gallery_second = !gallery_second;
}
The `onload` event switches images when an image has finished loading:
// This function triggers after the next image has loaded
function galleryLoaded() {
if (!gallery_switching)
return;
gallery_switching = false;
document.getElementById('gallery_b').style.opacity = gallery_second ? 1 : 0;
}
To start the rotation interval and display the initial image immediately:
setTimeout(galleryNext, 0); // Placeholder "onload"
setInterval(galleryNext, 2500); // Switch every 5 seconds
You can also set the initial `src` for the image elsewhere in your code.