为什么我的间隔只清除了一半?

Why is my interval clearing only halfway?

我一直在从事我的第一个主要编程项目,到目前为止进展顺利。我的目标是让动画 运行 直到事件被触发或 15 秒过去。动画超时后我想重复动画。我目前对该计划的解决方案如下所示。

    var animationSpeed = 40;
    var animationTimout = 375;
    var testTime = 1;
    //some more set up variables

    function onClick() {
        startDrive();
        setTimeout(startDrive, 15000); //****
    }

    function startDrive() {
        var Driving = setInterval(carDriving, aniSpeed);
    }

    function carDriving() {
        testLocation();
        drawCar();
        angleCalc();
        newLocation();
        getInfo();
    }

    function testLocation() {
        //this code gets information on whether or not the animation should be stopped
        testTime = testTime + 1

        if(a === 1 || testTime > animationTimeout) {
            //a test to cancel the animation, the other variables test to
            clearInterval(Driving);
        }
    }

    function drawCar() {
        //draws the car
    }

    function angleCalc() {
        //gets some info on how to move the car
    }

   function newLocation() {
        //decides on new coords for the car based on angleCalc();
    }

    function getInfo() {
        //gets some info I plan to use later in the project
    }

当我 运行 没有加星号的代码时,一切正常。如果满足停止条件,汽车会按照我的意愿进行动画处理并停止。车停在canvas的原地,好像间隔被清除了一样。当我添加带星号的代码行时,动画似乎可以运行,但它 运行 的速度是以前的两倍。我完全迷路了,我尝试的任何东西都不起作用。请帮忙。

问题可能是由于此处定义的局部变量引起的:

function startDrive() {
    var Driving = setInterval(carDriving, aniSpeed);
}

变量Driving只在函数startDrive中定义,它是一个局部变量,因为你在函数内部使用var来定义它。因此,当您尝试在 testLocation() 内访问它时,您访问的不是同一个变量。事实上,当您执行 clearInterval(Driving) 时,变量 Driving 未定义。一个简单的解决方案是通过删除 var:

使 Driving 全局化
function startDrive() {
    Driving = setInterval(carDriving, aniSpeed);
}

或者您可以将计时器作为参数传递到 testLocation 函数中。这样你就可以正确地清除间隔。