Search code examples
javascriptsettimeoutcleartimeout

ClearTimeout doesn't work when called at beginning of the function


I have a function that with a setTimeout. The very first part of the function sets the timeout to clear just in case it's called it again before the setTimeout fires.

The clearTimeout doesn't clear the timer. I've tested clearTimeout(spinTimer) after the part in the function where the setTimeout is called and it works. Why doesn't it work at the beginning?

I've declared the variable globally already:

var spinTimer;

function cakeCubeSpin(whereTo){

    clearTimeout(spinTimer);

    ... do some stuff

    switch(whereTo){
    case 1:
        var spinTimer = setTimeout( function(){
            $('#ccPanel4').css(leftReset);
            $('#ccPanel2').css(rightReset);
            $('#ccPanel3').css(backReset);
            $('#ccPanel1').css(frontReset);

            $('#cakeCubeWrapper').css(wrapReset);

            $('#ccPanel1').addClass('cc-current');
        }, ccSpeed);

    break;

    ... more stuff

}

Solution

  • You're re-scoping spinTimer with the following line:

    var spinTimer = setTimeout( function(){
    

    I think you meant:

    spinTimer = setTimeout( function(){