This is the official solution for Hands-on Project: Image Slideshow.
Overview
The solution script is divided into three functions, main(), preload() and changeImage(). The main() function calls the other two in order. First the preload() method is called and then changeImage(). Preloading continues to happen in background, while changeImage() executes.
Code
<html><head><title>Image slideshow using JavaScript</title><script>// array of URLs to be loadedvar urls = ["https://imgur.com/download/yAKnWJ2","https://imgur.com/download/6bsZq05","https://imgur.com/download/fY0iQZR","https://imgur.com/download/aCkT7TN","https://imgur.com/download/wgdprUW",];// initializationvar images = []; // array of imagesvar loaded = []; // whether or not loading is completefor (i = 0; i < urls.length; i++) {images.push(new Image());loaded.push(false);}var current = 0; // current image being displayedvar interval = 1; // time interval(in seconds) after which the next image should be displayedfunction changeImage() {if (!loaded[current]) {// wait for the current image to load// display the loading messagedocument.getElementById("loadmessage").innerHTML = "Still Loading Image " + (current+1) + " .... ";} else {// if current image has finished loading then do the followingdocument.getElementById("loadmessage").innerHTML = ""; // remove the loading message// Change Image// Note: If you change image when this image has not yet loaded// User will see a blank page / image coming in little bit at a timeslide = document.getElementById("slide");slide.innerHTML = ""; // remove previous imageslide.appendChild(images[current]); // show current image// Update current// Note: If you update current when this image has not yet loaded// then for really slow connections, the slideshow will 'skip' imagescurrent++;if (current == urls.length)current = 0;}}function preload(i) {// load the ith image in the images arrayif (i >= urls.length) {// all images have been loadedreturn;}images[i].src = urls[i]; // src set to the ith image in the images arrayimages[i].onload = function() {// when image has finished loading, set loaded[i] to trueloaded[i] = true;// call preload on the next image (i + 1)// Note: If you call preload(i+1) outside of onload, then ALL images// will load at the very beginning. This means, the user won't be able// to see _any_ image till _all_ of them load. That is not what you want!preload(i + 1);}}function main() {// the main functionpreload(0); // begin by preloading the first imagesetInterval(changeImage, interval * 1000); // call changeImage() every 1000 milliseconds}window.onload = main; // when the document has finished loading, call main.</script></head><body><div id="slide"></div><span id="loadmessage">Loading Image.... </span></body></html>