+ 9
Javascript if statement not working [Solved]
The alert('You lost') on the if condition rarely shows up. The other if's works well - link below. //code starts let detectContact = setInterval(()=>{ let characterTop = parseInt(window.getComputedStyle(character).getPropertyValue('top')) let blockLeft = parseInt(window.getComputedStyle(block).getPropertyValue('Left')) if( blockLeft == 50){ alert('you lost') console.log(blockLeft) } //code ends I'm trying to get an alert when the position left of the block is 50. I am really confused where the problem is. I think it's in setInterval() or window.getComputedStyle. https://code.sololearn.com/W89a21a8a7a1/?ref=app
3 Réponses
+ 3
Agontuk Noy [Less-Active] It's not guaranteed that the function registered in setInterval is going to land on any given frame, much less when blockLeft is at 50px.
The function will simply capture the block position at the time the function is called. In my case, it appears that the block moves 14px between each interval. This might be inconsistent between devices and perhaps between runs.
For this reason, you shouldn't target a condition based in the position being equal to 50 when using setInterval, but rather, consider using a range to cover pixels between something like 20 and 50:
if(blockLeft > 20 && blockLeft <= 50)
{...}
You can run my revised version of your code to see the blockLeft values on each interval when the position is between 0 and 100.
I hope this helps you understand what's going on. 😉👌
https://code.sololearn.com/WmFBqfEMp2v3/?ref=app
+ 4
There is a Set interval, but there is no clearInterval
+ 2
Check this:
https://code.sololearn.com/W7B7KamEXqD9/?ref=app