Why doesn’t this while loop work? (infinite)

Asked

Viewed 150 times

0

I’m having trouble with a while loop in my code. For some reason, it’s looping endlessly. This is the code:

function transf(){

var container = document.getElementById('container');
var compartimento = document.getElementById('compartimento');  

while (compartimento.childNodes.length > 0) {
container.appendChild(compartimento.childNodes[0]);
}  

var alturadocontainer = container.clientHeight;  
var containerlc = container.lastChild;    
var container2 = document.getElementById("container2");

while (alturadocontainer > 100){ 
container2.insertBefore(containerlc, container2.childNodes[0]);    
}

}

The first while loop works smoothly. The problem is in the second. The expected result is that as long as the container height was greater than 100, the last elements of the container would pass to the container2 (which in theory should decrease the height of the container, but it seems that this is not happening, thus causing the infinite loop). Why is this happening?

1 answer

0


View the adjustment by updating the value of the variables after the transfer:
I didn’t get to test the code.

function transf(){

var container = document.getElementById('container');
var compartimento = document.getElementById('compartimento');  

while (compartimento.childNodes.length > 0) {
container.appendChild(compartimento.childNodes[0]);
}  

var alturadocontainer = container.clientHeight;  
var containerlc = container.lastChild;    
var container2 = document.getElementById("container2");

while (alturadocontainer > 100){ 
container2.insertBefore(containerlc, container2.childNodes[0]);    
var alturadocontainer = container.clientHeight;  
var containerlc = container.lastChild; 
}

}
  • Thanks, Andrey! It worked! I’m very grateful.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.