How to prevent memory leak in javascript

I am stuck in a memory leak in js issues.

JavaScript:

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

here are my test codes, and I use tools.app to detect memory usage, and memory goes very fast.

I doubt that there are no variables in memory.

why?

any thought is appreciated.

+6
source share
1 answer

A set of closures is created in your code. This prevents the release of memory. In your example, memory will be released after all timeouts have completed.

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); 
+10
source

Source: https://habr.com/ru/post/910688/


All Articles