Search code examples
javascriptwhile-loopiterationinfinite-loopdo-while

How do I make an infinite while loop in JavaScript?


So I wanted to make a simple effect of snowflakes falling from the sky randomly. I can make them all fall at the same time with different velocities, but i cant seem to call for a while loop again only for +1 snowflake. Here is the link for the whole thing to give u an idea of what it should look like

Here is the code:

function createSnowflakes() {
    let i = 0;
    while (i < 30) {
        document.body.innerHTML += `<div  class="snowflake${Math.floor(Math.random()*10)} snowflakes"></div>`;
        i++
    }
    let snowflakes = document.querySelectorAll('.snowflakes');

    snowflakes.forEach((snowflake) => {
        snowflake.style.transform = `translateX(${window.innerWidth * Math.random()}px)`;
        snowflake.style.animation = `falling1 ${Math.floor(Math.random() * 8)+3}s linear forwards`;
    })

    snowflakes.forEach((elem) => console.log(elem));
    snowflakes.forEach((elem) => {
        elem.addEventListener('animationend', e => {
            elem.remove();
            snowflakes = document.querySelectorAll('.snowflakes');
            if (snowflakes.length < 10) {
                createSnowflakes();
            }
        })
        
    })
}

createSnowflakes();

Solution

  • You should use SetInterval() read more here. Here's a basic implementation. I also improved readability by using document.createElement and element.classList.add

    function createSnowflakes() {
        function create1Snowflake() {
          // document.body.innerHTML += `<div  class="snowflake${Math.floor(Math.random()*10)} snowflakes"></div>`;
          const snowflake = document.createElement("div")
          snowflake.classList.add(`snowflake${Math.floor(Math.random()*10)}`, "snowflakes")
          snowflake.style.transform = `translateX(${window.innerWidth * Math.random()}px)`;
          snowflake.style.animation = `falling1 ${Math.floor(Math.random() * 8)+3}s linear forwards`;
    
          snowflake.addEventListener('animationend', e => {
                snowflake.remove();
          })
          
          // add element to body
          document.body.appendChild(snowflake)
        }
        
      
        setInterval(() => {
          // make a snowflake
          create1Snowflake()
          
        }, 500)
    }
    
    createSnowflakes();
    

    To change how fast the snowflakes appear change the 500 inside of setInverval, but remember that it takes milliseconds not seconds.