I’m learning javascript and one of my exercises was to move box from left to right. It works fine first few cycles, but then it gets messy and I have no idea what causes that.
function preparePage(){
var box = document.getElementById("box");
var leftPosition = 0;
box.style.position = "absolute";
function animateRight(){
leftPosition += 1;
if (leftPosition<=300){
box.style.left = leftPosition+"px";
} else {
console.log("leftPosition = ",leftPosition);
clearInterval(intervalRight);
intervalLeft = setInterval(animateLeft, 20);
}
}
function animateLeft(){
if (leftPosition>=0){
leftPosition -=1;
box.style.left = leftPosition+"px";
} else {
console.log("leftPosition =", leftPosition);
clearInterval(intervalLeft);
setInterval(animateRight,20);
}
}
intervalRight = setInterval(animateRight,20);
}
window.onload = function(){
preparePage();
}
You forgot to put the handle for the interval moving right into the variable. When you start moving left the second time, it won’t stop the current inteval going right, it will try to stop the first interval again.
Change this:
into: