简体   繁体   中英

Does a recursive setTimeout call cause a closure chain memory leak?

I have the following scenario:

 let func = () => { //... let id = setTimeout(() => { console.trace(); clearTimeout(id); func(); }, 2000); } func(); 

If we run the following code in the Chrome console for example we get the following stack trace

console.trace
(anonymous) @ VM89644:4
setTimeout (async)
func @ VM89644:3
(anonymous) @ VM89644:6
setTimeout (async)
func @ VM89644:3
(anonymous) @ VM89644:6
setTimeout (async)
func @ VM89644:3
(anonymous) @ VM89644:6
setTimeout (async)
func @ VM89644:3
(anonymous) @ VM89644:6
setTimeout (async)
func @ VM89644:3
(anonymous) @ VM89644:6
setTimeout (async)
func @ VM89644:3
(anonymous) @ VM89644:6
...
...
...

which keeps increasing on every iteration. Eventually it reaches a maximum point (i think after 35 iterations) where the chain seems to stop growing but I'm curious if it's simply Chrome just not displaying it. What exactly is happening?

Does a recursive setTimeout call cause a closure chain memory leak?

No. After firing the timer each time, the timer subsystem in the browser releases its link to the timer function, which in turn releases its link to the environment where it was created, allowing them both to be reclaimed.

which keeps increasing on every iteration. Eventually it reaches a maximum point (i think after 35 iterations) where the chain seems to stop growing but I'm curious if it's simply Chrome just not displaying it. What exactly is happening?

This is standard memory management, things are cleaned up according to the JavaScript engine's heuristics for memory management, which don't always clean things up proactively. I suspect if you were repeatedly hitting devtools' "Collect Garbage" button (on the Memory tab), you'd notice it go back to near-baseline.

One thing that may prevent returning to near-baseline is V8's nifty async stack traces . They're advertised as "zero cost," but of course, that can't be completely true because they have to keep track of the async stack information (even if just as a string).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM