Memory leaks are usually the result of a design error that results in a loss of control over the segment of memory before it can be released, resulting in wasted memory. Here are some common causes of memory leaks

1. Global variables

Because JavaScript handles an undeclared variable by creating a reference to that variable on a global object. In the browser, the global object is the Window object. Variables are not released until the window closes or the page is refreshed, and if an undeclared variable caches a large amount of data, it can cause a memory leak.Copy the code

2. Circular references

In the js memory management environment, if object A has access to object B, it is called object A reference object B. The strategy for reference counting is to reduce "is the object no longer needed" to "does the object have other objects referring to it?" If no object refers to the object, the object will be reclaimed.Copy the code

3. The closure

Closures can cause the life cycle of an object reference to be removed from the context of the current function. If used improperly, closures can lead to circular references, similar to deadlocks, which can only be avoided, but cannot be resolved later, and will still leak memory even with garbage collectionCopy the code

4. Delay device/timer

This in setInterval/setTimeout refers to the window object, so internally defined variables are also mounted globally; The someResource variable is referenced in if, and the someResource will not be released if setInterval/setTimeout is not cleared. The same is true for setTimeout. So we need to remember to clearInterval/clearTimeout after use.Copy the code

5. Memory leaks caused by DOM

(1) The DOM reference is not cleared; (2) the attribute added to the DOM object is a reference to the object; (3) the binding event to the DOM objectCopy the code

6. Other reasons

Console. log printed objects cannot be garbage collected and may cause memory leaks.Copy the code

— — — — — — — — — — — — — — — — — — — —

How does the front end check for memory leaks?

(1). Use Chrome’s developer tool Profiles for snapshot comparison.

(2). In a Node environment, you can use the process.memoryUsage() method provided by Node to check for memory leaks

How do I handle memory leaks?

Memory leak caused by variable, remove variable a = null can be.

Memory leaks caused by event listening can be removed after listening.