ClearTimeout without ID

Is there a way to clear setTimeout() if it does not have an explicit identifier? The problem is that I am not allowed to change already running code and set timers without any handler.

Are JS "anonymous handlers" for them? Are these timers stored anywhere? Can I get any of these properties (the function that the timer is about to call? Time to be called?)

+4
source share
4 answers

No, you cannot do without help. You can try something REALLY hacky (don't do this, it's just an illusion of hacking) to clear all timeouts:

 for(var i=0; i<100000; i++) clearTimeout(i); 

but again, which is not flawless and far beyond hacks.

Decision? The fight can change the source, so you can do it right - or see if you can override the function that creates the timer.

+17
source

No. The clearTimeout method requires that the identifier returned from setTimeout be provided to remove the timeout.

Could you post more information about your script? Perhaps some snippets of code? Perhaps there is a way around the script.

+2
source

No. But you can force the handler to check if it should still handle the event (with a boolean variable).

0
source

Another possible hacker approach is to throw an error due to a timeout. For this to work, the error must be (a) not caught in the try-catch ; and (b) occur before the timeout has a chance to take actions that you do not like. Depending on the contents of the timeout, this can be easy, difficult or impossible.

For example, if the timeout is registered as follows:

 setTimeout(function(){ if(document.URL.toUpperCase() === "..."){ // do something that you don't like } }, 60000); 

then the only way (I think) that you can throw an error is to secure the String.prototype.toUpperCase function and check if the calling function is a timeout violation. You cannot do this check with absolute certainty, but (new Error).stack will certainly come in handy ... you can compare it with the expected stack trace. You can do similar things with the getter properties of the monkey nail, or perhaps by setting a specific object to undefined . ES6 may provide additional features.

This is clearly hacked, and in fact it does not clear the timeout, it only prevents its observed behavior. However, this can just do the trick! (If performance is important, then be careful with your monkey patches.)

0
source

All Articles