Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this script end in infinite loop?

I am trying to understand a code I found on the internet. I dont't understand in the while loop, why it is not an infinite loop. If change the calculator.appendChild in it to e.g. console.log it runs forever.

 window.location.hash = 1;
 var calculator = document.createElement("div");
 calculator.id = "height-calculator";
 while (document.body.firstChild) {
    calculator.appendChild(document.body.firstChild);
 }
 document.body.appendChild(calculator);
 document.title = calculator.clientHeight;

Basically there is always a first child in a non-empty site, so the condition is always true. Can someone explain why this way it doesn't run forever?

like image 360
B. Ma Avatar asked Nov 28 '19 11:11

B. Ma


People also ask

How do I turn off infinite loop in Chrome?

click Chrome DevTools window to get focus on it, pause script with F8, Ctrl+\ or by clicking Pause script execution button, press mouse button for 1-3 seconds on the button again to see more options, move click action to square stop button on expanded menu to stop permanently script execution.

How to stop infinite loop in shell?

Infinite while Loop You can also use the true built-in or any other statement that always returns true. The while loop above will run indefinitely. You can terminate the loop by pressing CTRL+C .

How to stop infinite loop in JavaScript?

An infinite loop will run forever, but the program can be terminated with the break keyword. In the below example, we will add an if statement to the while loop, and when that condition is met, we will terminate the loop with break .


2 Answers

A element can only be child of one other element.

calculator.appendChild(document.body.firstChild);

As soon as you attach document.body.firstChild to your calculator, it automatically detaches from body, so body will eventually run out of children.

like image 129
tkausl Avatar answered Oct 13 '22 00:10

tkausl


So process happens in 3 simple steps:

  1. var calculator = document.createElement("div"); this line creates a div OUTSIDE of the body in the DOM

  2. Then the loop moves all the children of body into the calculator which eventually ends unless body has infinite children which is not possible.

  3. document.body.appendChild(calculator); moves the calculator under body

So basically there are two major entities body and calculator, script moves all the children of body to calculator and then it moves calculator to body.

In other words script converts all children of body to the grandchildren of body and the only child of body becomes the calculator

I know I wrote too much but I myself understood it after a while, reading other comments and answers so I just wanted to leave it here for myself for future and for anyone else who needs more explanation to get it LOL

like image 25
Abhay Maurya Avatar answered Oct 13 '22 01:10

Abhay Maurya