Hacker Read top | best | new | newcomments | leaders | about | bookmarklet login
Does JavaScript's setInterval() method cause memory leak? (stackoverflow.com) similar stories update story
23 points by killahpriest | karma 750 | avg karma 5.24 2013-02-12 09:26:45 | hide | past | favorite | 13 comments



view as:

This is silly. You're creating a new anonymous function on every interval, so it will increasingly take up memory to hold these anon functions until the GC kicks in. It's doing exactly what it should do, because you don't want it doing GC every 50 ms.

It isn't creating a new anonymous function every interval. It's created once and passed in as an argument.

It's presumably the call stack that the memory is used for.


I don't think that's what's happening. The anonymous function is created just once, before calling setInterval, not within the callback itself.

That anonymous function is a literal, just like the number 50 (the next argument after it). In the same way the 50 doesn't get created each iteration, neither does the anonymous function.

The memory profile says otherwise, doesn't it? If you create a named function and call it like "setInterval(draw, 50)", the memory use stays constant.

Did you get that result on your machine? From all reports in that question the profile is the same regardless of the anonymous function.

Except it doesn't. At least, not when I try it.

My tenuous understanding of the ECMAScript spec would suggest that a new execution context and associated activation object + scope chain is created each time that function is invoked. Since this is a closure, the execution context and associated objects have to wait to be garbage collected.

So you're going to see an increase in memory with each function call until the garbage collector kicks in.

So while the function definition is a literal, the execution most definitely has a cost associated with it.


If it was an issue, wouldn't it be engine- or browser-specific?

Yes. Firefox had terrible GC pauses until last year [1]. Chrome processes just a portion of the heap at a time to reduce pauses to a minimum [2].

You can minimize GC by being clever about re-using objects, avoiding waste. The top answer shows how GC happens less frequently when using a setTimeout loop instead of setInterval, I don't know the underlying reason but that was always recommended before requestAnimationFrame came along.

These days you should use requestAnimationFrame whenever available - it allows the browser to plan ahead for a smoother framerate, adjust rate to the device capabilities, and save resources when it's in the background.

[1] http://phoboslab.org/log/2011/08/are-we-fast-yet [2] https://developers.google.com/v8/design#garb_coll


tl;dr : "No"

From what I can tell the issue stems from the fact that Javascript puts stack frames on the heap, which means the heap will grow with every function call, which they're doing every 50 ms.

Legal | privacy