JavaScript event listener memory leak

Viewed 3547

I'm working on a WebGL application using React, Redux and Three.js. My application uses mouse movements and clicks as input. Now for some reason, whenever I click or move the mouse, my application gets slower and slower. As shown in the performance profile below, there seems to be some kind of memory leak causing the memory used by event listeners to constantly grow.

enter image description here

As far as I understand, the yellow line in the screenshot shows the constantly growing memory usage for event listeners.

But what exactly does this yellow line represent? Is it the amount of memory used by event listeners? Or the number of registered listeners? Or the number of registered/unhandled events?

Has anybody experienced a similar problem in the past and maybe found the solution?

The full code of my application/prototype can be found in this repository. Unfortunately I haven't been able yet to isolate the cause of the issue or to reproduce it in a simple code snippet.

2 Answers

I've taken a quick look at your code, and my guess is you're passing => functions to something that adds the function as a listener, then later tries to remove it (here, for instance). You can't remove a => listener, since a new function will be created each time the render method is called (and therefore calling somewhere .removeEventListener(myArrowFunction) will try to match the function with one that's already been added, but they aren't equal.

Anyway, don't use arrow functions as listeners.

Edit : well, yeah, use arrow functions but declared as instance methods. Or stored as constants. Not as closures.

Related