Home > Blockchain >  How to set setInterval function to work with each separate element
How to set setInterval function to work with each separate element

Time:12-19

thanks for your time reviewing this question.

I am trying to display each image separately after a short break but seems like setTimeout or setInterval is not a good tool here, however, I googled all the available instruments but apparently these two are the only available. I can't use them since they will stack the function calls and will display all the elements at once. So then, I need to clear the redundant elements that is not what I expect my function to do.

I have the following code:

imagesToShow = document.getElementsByClassName("image-to-show");
let revealing;
console.log(imagesToShow);
for (const iterator of imagesToShow) {
  iterator.classList.add("isHidden");
}
const fadeIn = setTimeout(() => {
  for (const iterator of imagesToShow) {
    iterator.classList.remove("isHidden");
  }
}, 500);
.isHidden {
  display: none;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link rel="stylesheet" href="./Style/style.css" />
    <script src="./script/script.js" defer></script>
    <title>Banners</title>
    <style>
      .image-to-show {
        width: 400px;
        height: 400px;
      }

      .images-wrapper {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
      }
      .button-wrapper {
        height: 300px;
        margin-top: 100px;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .slide-stop,
      .slide-start {
        outline: none;
        border-radius: 50%;
        width: 100px;
        height: 100px;
        margin-right: 30px;
      }
    </style>
  </head>
  <body>
    <div >
      <img src="./img/1.jpg" alt="image of game"  />
      <img src="./img/2.jpg" alt="image of game"  />
      <img src="./img/3.JPG" alt="image of game"  />
      <img src="./img/4.png" alt="image of game"  />
    </div>
    <div >
      <button >Start slideshow</button>
      <button >Stop slideshow</button>
    </div>
  </body>
</html>

Could you please advise how to make sure it works with each element or maybe there is an alternative like "sleep" in C#. I need to display each and every element but it doesn't work correctly.

CodePudding user response:

The way your code is written, you are essentially waiting 500ms and then showing all the images at once.

You could set a timeout to show each image like so:

for (const i in imagesToShow) {
  setTimeout(() => imagesToShow[i].classList.remove("isHidden"), i * 500);
}

The i * 500 will show the first image after 0ms, second one after 500ms, third after 1000ms, etc.

  • Related