Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to prevent memory leak in javascript

i stuck into memory leak in js problems.

Javascript:

var index = 0;
function leak() {
    console.log(index);
    index++;
    setTimeout(leak, 0);
}
leak();

here is my test codes, and i use instruments.app to detect memory use of it, and the memory is going up very fast.

i am doubt that there seems no variables occupy the memory.

why?

any thought is appreciate.

like image 846
piggy_Yu Avatar asked Mar 14 '12 09:03

piggy_Yu


People also ask

How do I free up memory in JavaScript?

Hence there is no explicit way to allocate or free up memory in JavaScript. Just initializing objects allocates memory for them. When the variable goes out of scope, it is automatically garbage collected(frees up memory taken by that object.)

Can JavaScript cause memory leak?

Memory management is often neglected by developers due to misconceptions of automatic memory allocation by JavaScript engines, leading to memory leaks and, ultimately, poor performance. In this article, we'll explore memory management, types of memory leaks, and hunting memory leaks in JavaScript using Chrome DevTools.


1 Answers

Your code creates a set of closures. This prevents the release of memory. In your example the memory will be released after the completion of all timeouts.

This can be seen (after 100 seconds):

var index = 0;
var timeout;
function leak() {
    index++;
    timeout = setTimeout(leak, 0);
}

leak();

setTimeout(function() {
        clearTimeout(timeout);
}, 100000);

setInterval(function() {
        console.log(process.memoryUsage());
}, 2000);
like image 156
Vadim Baryshev Avatar answered Oct 30 '22 20:10

Vadim Baryshev