Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using setTimeout do you have to clearTimeout?

Tags:

javascript

Someone told me that when you use setTimeout you must clear it with clearTimeout. I can understand before the timeout runs out, but why after? Or is it untrue?

like image 364
NebulaFox Avatar asked Sep 12 '11 17:09

NebulaFox


People also ask

Do you need to clearTimeout after setTimeout?

No, you don't need to use clearTimeout if you intend for the timeout to be executed. The clearTimeout method is only used to stop timeouts from being executed. You can stop a timeout even if it has a time of 0 ms, because it won't be executed until you exit your function and return the control to the browser.

Is clearTimeout necessary in react?

Using SetTimeout Inside Of A React Component Is Easy Enough As It's Just A Regular JavaScript Method.,And An Example Of Clearing SetTimeout Inside Of A React Class Component:,Above All, It's Important That You Clear Timers, Otherwise You Could Experience Errors In Your Code.

Can we clearTimeout inside setTimeout?

clearTimeout() inside setTimeout() method not working in JS It does "work", but your logic is incorrect. After you called clearTimeout you are calling setTimeout again. Instead of calling clearTimeout you should just exit the function.

How do I set clearTimeout and setTimeout?

You need to pass the amount of time to wait for in milliseconds , which means to wait for one second, you need to pass one thousand milliseconds . 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.


1 Answers

It's not true - there's no harm in clearing a timeout after it has finished, but it's not necessary.

Per the specification:

If handle does not identify an entry in the list of active timers of the WindowOrWorkerGlobalScope object on which [clearTimeout] was invoked, the method does nothing.

In other words, it's a no-op; nothing happens, and no error will be thrown.

like image 76
jmar777 Avatar answered Oct 15 '22 21:10

jmar777