skip to Main Content

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 number of tweets which have been received, ( checks length of an array) and X is another which has it’s text content incremented by 1 every second.

  • I just put some random values for the time for it to take, I would use a more logical scale ( every 60 secs or something).

I wanted to log this information every minute, to make a graph but i’ve made an infinite loop somehow and i’m not quite sure how.

Here’s the code:

function saveinfo(){
var x = document.getElementsByClassName('timer')[0].textContent;
var y = document.getElementsByClassName('counter')[0].textContent;
while (x != "510"){
    if(x = "5"){
        console.log(y);

    }
    else if (x = "200") {
        console.log(y);

    }
    else if (x = "300"){
        console.log(y);

    }
    else if (x = "400"){
        console.log(y);

    }
    else if (x = "500"){
        console.log(y);
        x = "510"
    }
}
};

3

Answers


  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')

    Login or Signup to reply.
  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.
    Login or Signup to reply.
  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")

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search