You must clear the timeout variable each time

In my application, I use many setTimeout functions, so I am afraid that this will cause a formation problem:

setTimeout(function(){ // do something },0); 

And I found that people use this method:

 var t=setTimeout(function(){ // do something clearTimeout(t); }); 

I wonder if this is necessary?

+4
source share
4 answers

No, the object will be destroyed automatically (at least it should be). You must call clearTimeout when you need to delete an already set timeout.

Ex: you set a timeout of up to 5 seconds when any element hangs, but the user moves the cursor from the element until the timeout expires - so you need to delete the already initialized timeout.

+1
source

No, this is not necessary. Use clearTimeout() to schedule a timeout that is in the future (i.e., prevent it).

Eliminating a timeout after it has occurred (or while it is occurring) has no positive effect.

It'll be enough.

 setTimeout(function(){ // do something },0); 
+1
source

No no. A variable is needed only if you need to cancel the timeout before it occurs. Calling clearTimeout from within the callback has no effect, since there is no more time to stop.

+1
source

only if you want to cancel it before this happens - you can never stop with a delay of 0 ...

+1
source

Source: https://habr.com/ru/post/1383883/


All Articles