browser freezes with this js code, why?

You define numberOfFaces as 5, and then start a while loop which checks if that variable has a truthy value – anything above 0 is truthy. That variable will never change though, resulting in an infinite loop.

You need to decrement it somewhere inside the loop using numberOfFaces--; or similar. Maybe like this:

    var numberOfFaces = 5;
    function generateFaces() {
      while (numberOfFaces) {
        var smileFace = document.createElement("img");
        var random_number = Math.floor(Math.random() * 400);
        smileFace.src = ""; = random_number + "px"; = random_number + "px";

Maybe do a tutorial on while loops to help understand this more:

Note: Above while loop will stop when numberOfFaces becomes 0. In JS, 0 is falsy.

Leave a Comment