Skip to content Skip to sidebar Skip to footer

Why Is This While Loop Looping Infinitely?

So i'm making a web app for my studies, it basically uses a combination of Twitter's streaming api and Google Maps to display the Lat Lng values. Y is an element which states the n

Solution 1:

When your if statements are evaluated, you're setting x:

if(x = "5"){

This means that x will never equal "510", and your loop will go on forever.

To fix this, you should do something like if(x === '5')

Solution 2:

Three main reasons:

  • x is a local variable, not a reference to the content in the element. When the content changes, the value in x stays the same.
  • = is the assignment operator, not the comparison operator. You need to use == (or better, ===) for comparison. Since x = "5" evaluates to true, you will never get past the first if.
  • Your loop prevents the UI from updating anyway, because JavaScript is by default single-threaded. Even if you did read the value in the timer all the time rather than reading the local, it would still never change.

Solution 3:

Your if/else statements aren't working. You put in if(x = "200") instead of if( x == "200"). In if/else statements, if(x=1)doesn't work. if(x==1) or if(x=="1") always work. if(x==="1") works only if x is a string that says "1". if(x===1) only works if x is a number.

All you need to do is change the if(x="number") into if(x=="number")

Post a Comment for "Why Is This While Loop Looping Infinitely?"