Reputation: 1447
I defined a variable 'i' to be equal to 2, and then say: if 'i' is between 0 and 2, let the function 'animate' run. However, if I open up the console in JSFiddle (option-command-I), the console.log() continues decreasing by 1 below 0! Am I using the conditional in the if statement improperly?
var interval = window.setInterval(animate, 500);
var i = 2;
if (0 < i < 2) {
function animate() {
alert('run');
i--;
console.log(i);
}
}
JSFiddle: http://jsfiddle.net/lpsternotes/RuLHn/
Upvotes: 1
Views: 587
Reputation: 123739
You need to clear interval once you satisfy the condition and move the if condition (note that 0 < i < 2
needs to be split into 2 conditions joined with && but here you can just do) with modification inside the function.
var interval = window.setInterval(animate, 500);
var i = 2;
function animate() {
if (i > 0) {
console.log('run');
i--;
console.log(i);
}
else{
window.clearInterval(interval);
}
}
Upvotes: 3
Reputation: 6455
Why don't you put if statement inside your animate function?
var i = 2;
function animate () {
if (i> 0 && i<2) {
alert('run');
i--;
console.log(i);
}
}
Edit: 1) you might want to use i>0 && i<2 rather than 0
2) Not sure if you do need to clear the interval after the condition is met. Would be better if you could elaborate a bit more about your requirements.
Upvotes: 1
Reputation: 97678
There are two problems here.
Firstly, there is this: 0<i<2
. This will always evaluate to true
.
Why? What you hoped it meant was "i is between 0 and 2" (which could be written as 0<i && i<2
). But to a JS compiler, it is just two instances of the <
operator. First, 0<i
is evaluated, resulting in either true
or false
; then, that result is compared against <2
- so we have either true<2
or false<2
. In order to answer that question, JS must "cast" the true
or false
to an integer. It treats false
as 0
, and true
as 1
; since these are both <2
, the final result is always true
.
Secondly, there is the position of your if
statement, which is checked only once:
if (0 < i < 2) {
function animate() {
If you read through the code, you will see that there is no way of getting back to the line above this if
statement, since the only repeating part of the code is the interval repeatedly running the animate
function. To run each time the function runs, the if
needs to be inside the function
, not the other way around.
Upvotes: 4