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

I try to be a good citizen and hold on as much as possible globally. Is there a way to access setTimeout variables that are not in the global scope?

So, in this example, how does someone cancel the "timer"?

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

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

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

+5
source share
3 answers

You cannot, unless you have a reference to timerwhat you have not, because you are 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);

, . , .

+4

, . , :

myObject.timedAction = (function(){
    var timer;
    var result = function(){
        // do stuff
        // then wait & repeat       
        timer = setTimeout(myObject.timedAction,1000);
    };

    result.cancel = function() {
        clearTimeout(timer);
    };

    return result;
})();

myObject.timedAction();       // start it
myObject.timedAction.cancel() // end it

, . , , JS .

+3

:

myObject.timedAction = function(){
  // do stuff
  // then wait & repeat
  this.timer = window.setTimeout(function(){ myObject.timedAction(); },1000);
};

, , , , this.

, :

window.clearTimeout(myObject.timer);
+1

All Articles