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:
<script>
var numberOfFaces = 5;
function generateFaces() {
while (numberOfFaces) {
var smileFace = document.createElement("img");
var random_number = Math.floor(Math.random() * 400);
smileFace.src = "https://stackoverflow.com/questions/35727767/smile.png";
smileFace.style.top = random_number + "px";
smileFace.style.left = random_number + "px";
document.getElementById('leftSide').appendChild(smileFace);
numberOfFaces--;
}
}
</script>
Maybe do a tutorial on while
loops to help understand this more: http://www.tutorialspoint.com/javascript/javascript_while_loop.htm
Note: Above while loop will stop when numberOfFaces
becomes 0
. In JS, 0 is falsy.
2
solved browser freezes with this js code, why?