Sir
Sir

Reputation: 8280

Can't clearTimeOut

I have a TimeOut which doesn't stop once clear is used on it and I am unsure why.

This is my function:

function upgrade_bar(end, start, bar, timerId, func) {      

    var per = ( (new Date().getTime() / 1000) - start ) / ( end - start ) * 100;

    if(per>100)per=100;
    if(per<0)per = 0;

    if(per == 0) {
        bar.style.width = per + "%";
    } else if(per == 100) {
        clearTimeout(timerId); //this does not stop it
        if(func !== false){
            func(); //this does call at 100%
        }
    } else{
        bar.style.width = per+ "%";
    }
    console.log('still going');
    timerId = setTimeout(function() { upgrade_bar(end, start, bar, timerId, func) } , 17);
}

What have i misunderstood about this? Doesn't timerId hold the Id of the timeout for me to clear it?

Upvotes: 0

Views: 1136

Answers (2)

jcsanyi
jcsanyi

Reputation: 8174

setTimeout() just schedules one more execution of the function.

clearTimeout() can be used to stop an upcoming timeout before the time is reached - but once the timeout is reached and the function has been called, clearing the timeout does nothing - it wasn't going to run again anyways.

The problem here is that regardless of what happens in your function, you end by calling setTimeout again - scheduling it to run again.


A possible solution is to rewrite your function like this:

function upgrade_bar(end, start, bar, func){       
    var per = ( (new Date().getTime() / 1000) - start ) / ( end - start ) * 100;
    if (per>100) per=100;
    if (per<0) per = 0;

    bar.style.width = per + "%";

    if (per == 100) {
        if (func !== false) {
            func(); //this does call at 100%
        }
    } else {
        console.log('still going');
        setTimeout(function() { upgrade_bar(end, start, bar, func) } , 17);
    }
}

Upvotes: 2

Jason P
Jason P

Reputation: 27012

setTimeout() causes one execution of the specified function. You're thinking of setInterval(), which executes until canceled.

In your case, clearTimeout() is called, but the code continues on to set another timeout, no matter what code path is taken.

Try returning after calling func() to avoid setting the timeout again.

Upvotes: 0

Related Questions