My main program flow should be:
- read JSON (fetch api)
- do some stuff with json
- repeat
The problem is I cannot do a do - while because of the asynchronous nature of the fetch api.
Basically, the main() method below should repeat infinite
My code so far:
let playbook = [];
let slideIndex = 0;
let reinitialize = true;
function main() {
loadJSON().then(r => initializeSlideshow());
}
async function loadJSON() {
let response = await fetch('playbook.json');
if (response.status === 200) {
playbook = await response.json();
}
playbook.sort(function (x, y) {
return x.order - y.order;
});
}
function initializeSlideshow() {
playbook.forEach((photo, i) => {
//console.log(photo);
let div = document.createElement("div");
div.className = "mySlides fade";
div.style.display = "none";
let img = document.createElement("img");
img.src = photo.uuid;
img.style = "width:100% height:100%";
div.appendChild(img);
document.querySelector(".slideshow-container").appendChild(div);
})
startSlideShow();
}
async function startSlideShow() {
let slides = document.getElementsByClassName("mySlides");
slideIndex = 0
do {
console.log(playbook[slideIndex].enabled)
console.log(playbook[slideIndex].duration)
if (playbook[slideIndex].enabled == 'true') {
slides[slideIndex].style.display = "block";
//setTimeout(startSlideShow, playbook[slideIndex].duration); // Change image every 2 seconds
await new Promise(r => setTimeout(r, playbook[slideIndex].duration));
slides[slideIndex].style.display = "none";
}
slideIndex++;
}
while (slideIndex < slides.length)
}