Javascript while loop makes the page not load-Collection of common programming errors
Your code is an infinite loop if n !== 3
because nothing you do in the while loop ever changes the value of n so the while
loop just runs forever waiting for the value of n to become 3. It is unclear why you put it in a while
loop. It looks to me like it should just be an if
instead of a while
.
function checkiffinished() {
var n = $('.result-row').length;
if (n!==3)
{
$("span").text("There are " + n + " divs.");
};
}
If you are going to use a while loop, then you have to have something that actually changes the value of n in the loop and code that ensures that you will reach the condition in your while loop to prevent the infinite loop.
As others have said, if you want to regularly check for the value of 3, then you need to repeatedly execute this function using setTimeout or setInterval not just loop infinitely. But, you don’t want to execute it to often or you may drag down the performance of your site and other pages in the browser.
The best performing way to implement this would be just manually call checkiffinished()
any time you’ve modified the page. That way, no browser cycles would be wasted regularly checking the page value when nothing has changed and the page would be updated immediately after the change (no waiting for the next timer to fire to check the page).