Table of Contents
1. Global variables
2. Closure
3. The forgotten delayer/timer
When the dom is cleared or deleted, the event is not cleared) " >4. DOM element references that are not cleared (When the dom is cleared or deleted, the event is not cleared)
Home Web Front-end Front-end Q&A What are the causes of JavaScript memory leaks?

What are the causes of JavaScript memory leaks?

Nov 19, 2021 pm 04:37 PM
javascript memory leak

Causes of JavaScript memory leaks: 1. Improper use of global variables; 2. Improper use of closures; 3. Delays or timers are not cleared; 4. DOM element references that are not cleared (dom cleared or The event is not cleared when deleted).

What are the causes of JavaScript memory leaks?

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Memory leak means that a piece of allocated memory cannot be used or recycled until the browser process ends. This means that due to negligence or error, the program fails to release memory that is no longer used. Memory leaks do not refer to the physical disappearance of memory, but rather to the fact that after the application allocates a certain segment of memory, due to a design error, the control of the segment of memory is lost before the segment of memory is released, thus causing memory corruption. waste. Here are some common causes of memory leaks.

1. Global variables

JavaScript can handle undeclared variables: a reference to an undeclared variable creates a new variable in the global object. In the context of a browser, the global object is window.

function foo(){
  name = '前端曰';
}
// 其实是把name变量挂载在window对象上
function foo(){
  window.name = '前端曰';
}

// 又或者
function foo(){
  this.name = '前端曰';
}
foo() // 其实这里的this就是指向的window对象
Copy after login

In this way, an unexpected global variable is created unintentionally. To prevent this error from happening, add ‘use strict;’ at the front of your Javascript file. This enables a stricter mode of parsing JavaScript that prevents unexpected globals. Or pay attention to the definition of variables yourself!

2. Closure

Closure: Anonymous functions can access variables in the parent scope.

var names = (function(){  
    var name = 'js-say';
    return function(){
        console.log(name);
    }
})()
Copy after login

Closing will cause the life cycle of the object reference to be separated from the context of the current function. If the closure is used improperly, it can lead to a circular reference (circular reference), similar to a deadlock, which can only be avoided and cannot be solved after it occurs. , even with garbage collection, memory leaks will still occur.

3. The forgotten delayer/timer

In our daily needs, we may often try setInterval/setTimeout, but we usually forget to clean it up after use.

var someResource = getData(); 
setInterval(function() { 
    var node = document.getElementById('Node'); 
    if(node) { 
        // 处理 node 和 someResource 
        node.innerHTML = JSON.stringify(someResource)); 
    } 
}, 1000);
Copy after login

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

4. DOM element references that are not cleared (When the dom is cleared or deleted, the event is not cleared)

var elements = {
    button: document.getElementById('button'),
    image: document.getElementById('image'),
    text: document.getElementById('text')
};
function doStuff() {
    image.src = 'http://some.url/image';
    button.click();
    console.log(text.innerHTML);
}
function removeButton() {
    document.body.removeChild(document.getElementById('button'));
    // 此时,仍旧存在一个全局的 #button 的引用
    // elements 字典。button 元素仍旧在内存中,不能被 GC 回收。
}
Copy after login

[Recommended learning: javascript Advanced Tutorial

The above is the detailed content of What are the causes of JavaScript memory leaks?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Go memory leak tracking: Go pprof practical guide Go memory leak tracking: Go pprof practical guide Apr 08, 2024 am 10:57 AM

The pprof tool can be used to analyze the memory usage of Go applications and detect memory leaks. It provides memory profile generation, memory leak identification and real-time analysis capabilities. Generate a memory snapshot by using pprof.Parse and identify the data structures with the most memory allocations using the pprof-allocspace command. At the same time, pprof supports real-time analysis and provides endpoints to remotely access memory usage information.

Solve the memory leak problem caused by closures Solve the memory leak problem caused by closures Feb 18, 2024 pm 03:20 PM

Title: Memory leaks caused by closures and solutions Introduction: Closures are a very common concept in JavaScript, which allow internal functions to access variables of external functions. However, closures can cause memory leaks if used incorrectly. This article will explore the memory leak problem caused by closures and provide solutions and specific code examples. 1. Memory leaks caused by closures The characteristic of closures is that internal functions can access variables of external functions, which means that variables referenced in closures will not be garbage collected. If used improperly,

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to avoid memory leaks in Golang technical performance optimization? How to avoid memory leaks in Golang technical performance optimization? Jun 04, 2024 pm 12:27 PM

Memory leaks can cause Go program memory to continuously increase by: closing resources that are no longer in use, such as files, network connections, and database connections. Use weak references to prevent memory leaks and target objects for garbage collection when they are no longer strongly referenced. Using go coroutine, the coroutine stack memory will be automatically released when exiting to avoid memory leaks.

How to detect memory leaks using Valgrind? How to detect memory leaks using Valgrind? Jun 05, 2024 am 11:53 AM

Valgrind detects memory leaks and errors by simulating memory allocation and deallocation. To use it, follow these steps: Install Valgrind: Download and install the version for your operating system from the official website. Compile the program: Compile the program using Valgrind flags (such as gcc-g-omyprogrammyprogram.c-lstdc++). Analyze the program: Use the valgrind--leak-check=fullmyprogram command to analyze the compiled program. Check the output: Valgrind will generate a report after the program execution, showing memory leaks and error messages.

Debugging techniques for memory leaks in C++ Debugging techniques for memory leaks in C++ Jun 05, 2024 pm 10:19 PM

A memory leak in C++ means that the program allocates memory but forgets to release it, causing the memory to not be reused. Debugging techniques include using debuggers (such as Valgrind, GDB), inserting assertions, and using memory leak detector libraries (such as Boost.LeakDetector, MemorySanitizer). It demonstrates the use of Valgrind to detect memory leaks through practical cases, and proposes best practices to avoid memory leaks, including: always releasing allocated memory, using smart pointers, using memory management libraries, and performing regular memory checks.

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

How to effectively avoid memory leaks in closures? How to effectively avoid memory leaks in closures? Jan 13, 2024 pm 12:46 PM

How to prevent memory leaks in closures? Closure is one of the most powerful features in JavaScript, which enables nesting of functions and encapsulation of data. However, closures are also prone to memory leaks, especially when dealing with asynchronous and timers. This article explains how to prevent memory leaks in closures and provides specific code examples. Memory leaks usually occur when an object is no longer needed but the memory it occupies cannot be released for some reason. In a closure, when a function refers to external variables, and these variables

See all articles