4

I have been working on my first major programming project and so far it has been going pretty well. My goal is to have an animation run until either an event is triggered or 15 seconds have passed. After the animation times out I want to animation to repeat. My current solution to the plan is shown below.

    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
    }

When I run the code without the starred line, the whole thing works. The car animates as I want it to and stops if the conditions for stopping are met. The car freezes where it was on the canvas, and it seems as if the interval was cleared. When I add the starred line of code, the animation seems to work, but it runs twice as fast as before. I am utterly lost and nothing I try works. Please help.

Ori Lentz
  • 3,668
  • 6
  • 22
  • 28
Groodyandruff
  • 73
  • 1
  • 3

1 Answers1

3

The problem is likely due to the local variable defined here:

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

The variable Driving is only defined in the function startDrive, it's a local variable because you are using var to define it inside the function. So when you attempt to access it inside testLocation() you are not accessing the same variable. In fact when you do clearInterval(Driving) the variable Driving isn't defined. A simple solution would be to make Driving global by removing the var:

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

Or you can pass the timer as a parameter inside the testLocation function. This way you will be clearing the interval properly.

Spencer Wieczorek
  • 21,229
  • 7
  • 44
  • 54