Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to reveal an element when an setInterval ends?

I would like to reveal an element ("hidText") when the current setInterval ("fillUp") ends. I tried to add an if function into the fillUp function but it won’t execute. Is there anyway to fix this? Thanks!

let blankSquare = document.querySelectorAll(".square");
let hidText = document.querySelector(".hidText");

let index = 0;

function fillUp() {
  setInterval(() => {
    blankSquare[index++].classList.add("fill")

  }, 1000);
  if (index >= 4) {
    hidText.classList.add("display")
  }

}

fillUp();
.square {
  margin: 1vh;
  height: 3vh;
  width: 3vh;
  background-color: none;
  border: solid 2px grey;
}

.fill {
  background-color: grey;
}

.hidText {
  display: none;
}

.display {
  display: all;
}
<div class="squares">
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
</div>
<p class="hidText"> Hello There </p>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Use display: block; instead.

Also, don’t forget to clear the interval else it will continue indefinitely.

let blankSquare = document.querySelectorAll(".square");
let hidText = document.querySelector(".hidText");

function fillUp() {
  let index = 0;
  const timer = setInterval(() => {
    blankSquare[index++].classList.add("fill")
    
    if (index >= blankSquare.length) {
      clearInterval(timer)
      hidText.classList.add("display")
    }
  }, 1000);
}

fillUp();
.square {
  margin: 1vh;
  height: 3vh;
  width: 3vh;
  background-color: none;
  border: solid 2px grey;
}

.fill {
  background-color: grey;
}

.hidText {
  display: none;
}

.display {
  display: block;
}
<div class="squares">
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
</div>
<p class="hidText"> Hello There </p>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading