+ 2
JavaScript clearInterval / if statement help
This is a snippet from some code I'm working on. I can't figure out why I'm not getting inside the 'if' statement to execute clearInterval(t). The intervals just keep going. Any help appreciated. I've included debug alerts where you can see the test returns true after the 4th interval. https://code.sololearn.com/W63ID9lG6cz5/?ref=app
4 Answers
+ 4
Hi @Duncan... The issue is with your conditional check.
If moveNext is set to 3, then the condition will only be true after counter increments to 4.
It is also important to note that it will take 5 intervals before this condition is true. The reason is your counter is initialized at 0. Notice all the values of counter before the condition is satisfied:
(counter > moveNext)
1) counter is 0
2) counter is 1
3) counter is 2 - (Target stop for moveLimit set to 3.)
4) counter is 3
5) counter is 4 --> (Condition will NOT be true until the 5th interval.)
Step 1: Change your operator to " >= " so the condition will be true on the 4th interval when counter is 3 or higher.
(counter >= moveNext)
1) counter is 0
2) counter is 1
3) counter is 2 - (Target stop for moveLimit set to 3.)
4) counter is 3 --> (Condition will NOT be true until the 4th interval.)
Step 2: Your goal is for move() to be limited to only 3 intervals. Since you are working with a zero based counter, you will want to compare counter to moveLimit reduced by 1.
The updated condition will now satisfy the intended behavior as expected:
(counter >= moveNext-1)
1) counter is 0
2) counter is 1
3) counter is 2 --> (Condition will NOW be true on the 3rd iteration.)
Also, a better way to visualize this in Code Playground is with document.write() instead of alert().
https://code.sololearn.com/WVB4aP6s06Qh/#js
+ 3
Awesome! I'm glad this made sense. I wrote it when I was really tired. The reason I spent so much time on the details was because I could tell you were trying to understand why the loop wasn't working the way you expected it to work. Rather than simply give you the fix, I figured you were looking for the "why".
Also, feel free to mark that as the accepted answer by selecting the checkmark next to my previous response. That is, if you believe it to be the right answer. đ
+ 2
Sure was looking for the "why", so thanks again for taking the time it's much appreciated. I like to understand how things work so I make best use of them.
Response 'ticked' đ
+ 1
Thank you so much David, that's a brilliant explanation. After looking at your code and rechecking mine it makes sense now :)