Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How to clear a non-global (closured) setTimeout?

I'm trying to be a good citizen and keep as much out of the global scope as possible. Is there a way to access setTimeout variables that are not in the global scope?

So that, in this example how would someone cancel 'timer'?

myObject.timedAction = (function(){
    var timer;
        return function(){
            // do stuff

            // then wait & repeat       
            timer = setTimeout(myObject.timedAction,1000);
        };
})();

I've tried clearTimeout(myObject.timedAction.timer,1000); (without success), and not sure what else to try.

like image 344
americruiser Avatar asked May 08 '11 01:05

americruiser


People also ask

Can we clear setTimeout in JavaScript?

The clearTimeout() method clears a timer set with the setTimeout() method.

How do I clear timeout after setTimeout?

To cancel a setTimeout() method from running, you need to use the clearTimeout() method, passing the ID value returned when you call the setTimeout() method.

What happens if setTimeout is not cleared?

In other words, it's a no-op; nothing happens, and no error will be thrown. Save this answer. Show activity on this post. You don't actually need to use clearTimeout , you only use it if you wish to cancel the timeout you already set before it happens.

Does clearTimeout clear all timeouts?

The global clearTimeout() method cancels a timeout previously established by calling setTimeout() . If the parameter provided does not identify a previously established action, this method does nothing.


1 Answers

You can't unless you have a reference to timer, which you don't because you're declaring it as a variable in a scope. You can do something like:

myObject.timedAction = (function(){
    return function(){
        // do stuff

        // then wait & repeat       
        myObject.timedAction.timer = setTimeout(myObject.timedAction,1000);
    };
})();

clearTimeout(myObject.timedAction.timer);

Note that the above code will only ever allow ONE timer. If you need references to more than one timer, it needs to be adjusted.

like image 128
Nobody Avatar answered Sep 20 '22 00:09

Nobody