treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Stopping a loop

  • Hello beautiful people!

    Right, so I'm working on some code for a tiny little game, and I was wondering if it's possible to stop a loop which generates elements. When they the meteors collide with "felix" (I have function for that), a game over overlay is shown, but I need to stop that loop from running forever.

    function createMeteor() {
    
      for(var i; i=0; i < 1; i++) {
        var meteor = document.createElement("div");
        meteor.className = "meteor";
        document.getElementById("game").appendChild(meteor);
        meteor.style.left = randomPosition(0, 540) + "px";
        meteor.style.top = document.getElementById("game").offsetHeight + "px";
      }
    }
    

    Is it possible to stop this function createMeteor or the loop inside it?

    Thanks in advance!

  • I feel like I'm missing something here. What is the point of having a for loop when you only have one element?

  • Maybe because it's a game he only wants it to run once in this particular case but may need it to run more than once somewhere else. I have no idea.

  • Use a 'while' loop, not a for loop