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.
The clearTimeout() method clears a timer set with the setTimeout() method.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With