JavaScript / callback object lifetime with onload event

Today I am coding a gallery of images, and this led me to a philosophical question.

I create a preloaded Image object and set the onload event for it

... onmouseover = function() { preloadActive = true; imgPreload = new Image(); imgPreload.onload = function() { preloadActive = false; } imgPreload.src = ...; } 

Where imgPreload and preloadActive are global variables

Now imagine that before starting onload() new onmouseover() triggered.

a line of code is launched that creates a new image object, the old image object loses the last link and goes to Erebus and waits for the garbage collector to eat it.

Question here: A copy of the old object is not destroyed immediately. The onload event continues to live, no one knows how long? Do you have cross browser experience?

Thanks!

PS: I'm not worried about IE6


PPS: what happens if I have an object with the setInterval timeout id inside?

 obj.someVar = setInterval(...) 

SetInterval parameter is set at the very moment when I execute

 obj = {} 

?

+4
source share
1 answer

Well, for starters, global variables are not allowed to garbage collect (which is usually the cause of memory leak problems and is one of many reasons to avoid using global variables all together).

Having said that, read this article by Eric Lippert. It is old, but I still think it is very relevant.

+4
source

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


All Articles