Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there memory leak issue if not calling clearTimout after calling setTimeout

Tags:

javascript

After calling setTimeout, is there memory leak issue without calling clearTimeout?

Thanks.

like image 688
Ricky Avatar asked Nov 22 '10 10:11

Ricky


People also ask

Can setTimeout cause memory leak?

This is technically a memory leak because there is no longer any direct reference to the setTimeout function so that you could clear it later (kind of a zombie timeout if you will).

Do you need to call clearTimeout?

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. It's usually more practical to use clearInterval with setInterval because setInterval usually runs indefinitely.

What causes memory leak reaction?

Memory leaks in React applications are primarily a result of not cancelling subscriptions made when a component was mounted before the component gets unmounted. These subscriptions could be a DOM Event listener, a WebSocket subscription, or even a request to an API.


2 Answers

No. clearTimeout only needs to be called if you want to stop a pending setTimeout from happening. After the setTimeout happens, the timer id is no longer valid but fortunately calling clearTimeout with an invalid timer id is harmless.

If you see memory leaks happening the problem is somewhere else.

like image 98
slebetman Avatar answered Sep 27 '22 18:09

slebetman


There are times when setTimeout can cause memory leaks... see the following article: setTimeout memory leaks

Be warned that IEx has a garbage-collector subtlety, though; I think that if you reference a DOM variable in a Javascript closure, then the collection mechanism gets confused and it doesn't get trashed at the end of the request: eventually this becomes a memory leak. I think it's because DOM variables and internal JS variables get collected by two different collectors, and they don't communicate properly about what's no longer being used.

I think you can fix this by setting the variable to null:

setTimeout(function(){
    myFunction(parameter); 
    parameter = null
}, myTimeout);

This explicitly sets the garbage collection in motion.

like image 39
crazyDiamond Avatar answered Sep 27 '22 18:09

crazyDiamond