0

I want the user to enter a specific number and display that many images with the help of Unsplash API, but when the function calling the API is called there is a gap of 5 seconds before images finally appear on screen, and in that gap, I want to display a gif(loader) and hide it when images are finally visible on DOM, but I am not able to achieve this, can someone help

let imgNum = document.querySelector('#num')
let btn = document.querySelector("#btn")
let output = document.querySelector("#output")
let loadImg = document.querySelector("#load") // gif image
let url = "https://source.unsplash.com/random"
loadImg.style.visibility = 'hidden';

function disLoad() {
  loadImg.style.visibility = 'visible';
}

function hideLoad() {
  loadImg.style.display = "hidden"
}

function displayFunc() {
  disLoad()
  let img = ""
  for (let i = 0; i < Number(imgNum.value); i++) {
    let newImg = `<img src=${url}>`
    img += newImg
  }
  hideLoad()
  output.innerHTML = img
}
btn.addEventListener("click", displayFunc)
<!-- GIF in HTML -->
<div id="num"></div>
<button id="btn">button</button>
<div id="output">
  <img src="https://media.tenor.com/lwoULCdn-y4AAAAC/placeholder-text.gif" id="load">
</div>
Michael M.
  • 10,486
  • 9
  • 18
  • 34

1 Answers1

0

This is because the UI and your JS run on the same thread, so you add and remove the loading gif (after your processing is complete!) without the UI showing it.

You would need to add the gif and then run your processing, as a separate function, within a setTimeout() with a timeout of 0.

Detailed answer here

Sean Conkie
  • 127
  • 1
  • 8