我试着把盒子从左移到右,然后再移回来,但它在几个周期后崩溃了

I try to move box from left to right and back again, but it crashes after a few cycles

本文关键字:崩溃 周期 几个 盒子 左移 然后 回来      更新时间:2023-09-26

我正在学习javascript,我的一个练习是将盒子从左移到右。刚开始的几个周期很好,但后来就乱了,我不知道是什么原因造成的。

    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();
    }

您忘记将用于间隔移动的句柄放入变量中。当你第二次开始向左移动时,它不会阻止当前间隔向右移动,它会尝试再次停止第一个间隔。

改变:

setInterval(animateRight,20);

为:

intervalRight = setInterval(animateRight,20);