Home > Enterprise >  setInterval / setTimeout for revealing elements one by one
setInterval / setTimeout for revealing elements one by one

Time:07-27

I have a simple for loop inside a rendering function.

        for (let i = 0; i < PLAYER.hand.length; i  ) {
      
        playerHTML  = `<img class='card' src='images/cards/${PLAYER.hand[i]}.svg'>`;
    }

I am trying to implement a card draw animation. How can I implement that? I tried for example:

for (var i = 0; i < PLAYER.hand.length; i  ) {
(function(i) {
    setInterval(function() {
      playerHTML  = `<img class='card' src='images/cards/${PLAYER.hand[i]}.svg'>`;
    }, 5000)
})(i)}

did not work for me. any ideas?

CodePudding user response:

you are already using interval so probably dont need the for loop

(function() {
    let i = 0;
    const interval = setInterval(function() {
      playerHTML  = `<img class='card' src='images/cards/${PLAYER.hand[i]}.svg'>`;
      i  = 1;
      if (i >= PLAYER.hand.length) {
          clearInterval(interval);
      }
    }, 5000)
})()

CodePudding user response:

If you are looping through the player hand like that, your code will create an interval for each of the element and add them to playerHTML every 5000ms.

You can achieve what you want throught the use of setInterval and manually tracking/increasing the current index like this:

let i = 0
let maxLen = 5 // amount of cards on player hand
let interval = 1000

const myInterval = setInterval(() => {
  console.log(i) // add to player hand
  i   // go to next card
  if (i >= maxLen) { // breaking out of interval condition
    clearInterval(myInterval);
  }
}, interval)

CodePudding user response:

Another approach could be to initially load all the images but not display them. Then, in a setInterval() loop the existing hidden class could be removed from every element, one by one:

const cont=document.querySelector(".content");
cont.innerHTML=[...Array(5)].map((_,i)=>
  `<img src="https://picsum.photos/id/${237 i}/150/100" >`).join("<br>");

const intv = setInterval(() => {
 const img=cont.querySelector(".hidden");
 if(img) img.classList.remove("hidden");
 else clearInterval(intv);
},1000)
.hidden {display:none}
<div ></div>

  • Related