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
When your
if
statements are evaluated, you’re settingx
: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')
Three main reasons:
x
is a local variable, not a reference to the content in the element. When the content changes, the value inx
stays the same.=
is the assignment operator, not the comparison operator. You need to use==
(or better,===
) for comparison. Sincex = "5"
evaluates totrue
, you will never get past the firstif
.Your if/else statements aren’t working.
You put in
if(x = "200")
instead ofif( x == "200")
.In if/else statements,
if(x=1)
doesn’t work.if(x==1)
orif(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")
intoif(x=="number")