问题
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"
}
}
};
回答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')
回答2:
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 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.
回答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")
来源:https://stackoverflow.com/questions/36460244/why-is-this-while-loop-looping-infinitely