hguser
hguser

Reputation: 36028

is it necessary to clear the timeout variable each time

In my application,I use many setTimeout function,so I am afraid if it will cause peformance problem:

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

And I found people use this manner:

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

I wonder if it is necessary?

Upvotes: 4

Views: 952

Answers (4)

Samich
Samich

Reputation: 30125

No, object will be destroyed automatically (at least should be). You need to call clearTimeout when you need to remove already set timeout.

Ex: you have set timeout to 5 seconds on hovering some element but user moves out cursor from element before timeout elapsed - so you need to remove already initialized timeout.

Upvotes: 1

Leon
Leon

Reputation: 4532

only if you want to cancel it before it happens - which you'll never be able to stop with a delay of 0...

Upvotes: 1

Guffa
Guffa

Reputation: 700382

No, it's not. The variable is only needed if you need to cancel the timeout before it happens. Calling clearTimeout from inside the callback has no effect, as there is no longer a timeout to stop.

Upvotes: 1

Tomalak
Tomalak

Reputation: 338228

No this is not necessary. Use clearTimeout() to un-schedule a timeout that's still in the future (i.e. to prevent it from happening).

Clearing a timeout after it has happened (or while it is happening) has no positive effect.

This will suffice.

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

Upvotes: 2

Related Questions