I am writing a bicycle, the cube should move to the right endlessly and return. Only 1 iteration occurs. If you add left_go () to else if {setInterval (right_go, 5);}, everything works, but over time the animation starts to slow down and hang. Help me please?

var animate_right = setInterval(right_go, 5); function right_go () { var left_padding = cube_style.left; if (left_padding!=width_square){ cube.style.left = x +"px"; x++; console.log(left_padding); } else if(left_padding=width_square){ clearInterval(animate_right); var animate_left = setInterval(left_go, 5); } } function left_go (animate_left) { var left_padding = cube_style.left; if (left_padding!='-1px'){ cube.style.left = x +"px"; x--; console.log(left_padding); } else if(left_padding!=width_square){ clearInterval(animate_left); } } 
  • one
    I will say from experience that it is better not setInterval use setInterval , but to use recursive setTimeout - Aliaksandr Pitkevich

1 answer 1

Both variables, animate_left and animate_right , must be global, and you have clearInterval(animate_left); does nothing, as the variable animate_left is not defined at this location. Accordingly, timers with left_go every 5 milliseconds accumulate, and everything slows down.

The code should be symmetrical with respect to left and right .

 var animate_right = setInterval(right_go, 5); var animate_left = null; function right_go () { var left_padding = cube_style.left; if (left_padding!=width_square){ cube.style.left = x +"px"; x++; console.log(left_padding); } else if(left_padding=width_square){ clearInterval(animate_right); animate_left = setInterval(left_go, 5); // !!! no var } } 
  • should the animate_left and animate_right be defined as setInterval or something else? If you define them through setInterval, they both start and start to conflict with each other and the cube on the spot is twitching. - Vladimir
  • Thank you very much, everything worked! - Vladimir