styke
styke

Reputation: 2174

Why is clearTimeout not working for this code?

I call the following code on mouse click:

clearTimeouts();
var inMotion = true, x = 0;
var shuffleTimer = setTimeout(function(){inMotion = false}, 3500);
var shuffleStart = setTimeout(oneShuffle, x);

function oneShuffle(){
    x+=5;
    if(inMotion === true){

        console.log('Shuffling again');

        //shuffle again
        shuffleStart = setTimeout(oneShuffle, x);

    } else {

        //increment spins
        spins++;

        //reset spins if loadOrder been exhausted
        spins === loadOrder.length ? spins = 0 : 0;

        console.log(spins);

    }
}

function clearTimeouts(){
   console.log('Clearing timeouts')
   clearTimeout(shuffleTimer);
   clearTimeout(shuffleStart);
}

What should be happening is if I click the elment while inMotion is true the two timeouts should reset and my spins counter should not increase for the previous click. However, what happens instead is that spins gets incremented for the previous timeouts anyway. Why?

Upvotes: 0

Views: 302

Answers (2)

Roger Barreto
Roger Barreto

Reputation: 2284

You should put clearTimeouts() inside your if, like this:

if(inMotion === true){
    clearTimeouts();
    console.log('Shuffling again');

    //shuffle again
    shuffleStart = setTimeout(oneShuffle, x);

}

Upvotes: 0

Boris B.
Boris B.

Reputation: 5024

What timers should reset? If the code you posted is in a click handler, then each click produces new timers.

The lines:

var shuffleTimer = setTimeout(function(){inMotion = false}, 3500);
var shuffleStart = setTimeout(oneShuffle, x);

create new timers each time, so the first line (clearTimeouts();) makes no sense since the timers don't exist until next two lines.

You should put both timers outside the scope of a click handler, so all click invocations would reference same timers. Also all state (inMotin, spins, etc.) should exist outside the function scope, otherwise each click produces new, unrelated variables.

Upvotes: 2

Related Questions