I have a simple JavaScript file that gets multiple image files from a local device and displays a thumb of the images. So far so good.
Once the thumbs are displayed I have a button that calls the addImages() function. I need to display a slide show of the images, one at a time, for 3 seconds. However, what is happening is all the images are showing at the same time, then the sleep function is called, and then remove the image. Here is my code:
function addImages() {
var preview = document.querySelector('#display');
async function readAndPreview(file) {
var reader = new FileReader();
reader.addEventListener("load", async function () {
var image = new Image();
image.height = 400;
image.width = 400;
image.title = file.name;
image.border = 5;
image.src = this.result;
preview.appendChild(image);
sleep(3000).then(()=> preview.removeChild(image))
}, false);
reader.readAsDataURL(file);
}
if(files) {
[].forEach.call(files, readAndPreview);
}
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
It looks like the code iterates through to appendChild and then starts again until all images are added and then calls the sleep functions and then removeChild. Why???
Any help will be appreciated. Thanks.