0

I edit the code as shown below to make the red box go back and forth, it start fine, but theres some glitch when I run it longer

//calling the function in window.onload to make sure the HTML is loaded window.onload = function() { var pos = 0; //our box element var box = document.getElementById('box'); var t = setInterval(move, 10); function move() { if(pos >= 150) { t = setInterval (reverse, 10); } else { pos += 1; box.style.left = pos+'px'; } } function reverse() { if(pos == 0) { t = setInterval(move, 10); } else { pos -= 1 box.style.right = pos + 'px'; } } }

6th Sep 2019, 4:14 AM
R M
3 Respuestas
+ 3
Use setTimeout instead
6th Sep 2019, 5:52 AM
Calviղ
Calviղ - avatar
+ 3
Solution: Insert clearInterval(t); before setInterval in the two functions Fixed code : https://code.sololearn.com/WwLv4fv6KlMk/?ref=app Explanation : The interval, when not cleared, stacks up. So, the box is trying to move both left and right at the same time. The motion does not show this, but the calculations in the CPU really exists, thus the animation lags soon. Example : https://code.sololearn.com/WWnwg5aE5dlr/?ref=app In Mode 1, when you touch the screen, setInterval is triggered. Compare the speed at tapping only once and tapping many times, you can see the speed increases. The increase is not because a different speed argument is passed to the looping function, instead it is that the looping function is being called multiple times during one interval. A second fix: In the function reverse, you shouldn't set right, because you are decreasing pos, so you should keep setting left.
6th Sep 2019, 10:42 AM
Gordon
Gordon - avatar
0
can anybody help to explain why it happened?
6th Sep 2019, 4:15 AM
R M