welcome to Red Stapler in this video we are going to show a basic example of how
javascript can cause a memory leak and how to find it memory leaks can happen
in many ways but essentially it's a situation that the memory are allocated by
the program or script cannot be free back to operating system in this case
is web browsers let's take a look at the example I have two buttons start and
stop the start button then click it will call grow function which will append a
string of 1 million X chars long now you see that the variable here is
defined as global a global variable cannot be freed by the garbage collector
process so it will stay in a memory as long as you still on a page and also the
grow function will call itself recursively every 1 second and a stop
button will change the running flag to false and stop the recursive call now
I'm going to run this while recording the memory usage and see what will
happen in Chrome open the developer tools by pressing f12 then go to the
performance tab click the record button and run the code now let's wait for
about 15 seconds after that I will stop the code and wait for another 10 seconds
obviously the JavaScript heap usage is going up after time the spike here is
when the grow function was called because there's a lot of background
operation going on during the string processing and you will see the
immediate drop this is when a garbage collector was running which able to
clear that most of the garbage except one the X variable that we have defined
as global so it kept growing and growing and even after we stopped the memory
usage was not going down because the global scope now let's change things
around a little bit I'm going to put the grow function and X variable inside the
click event handler and retest the code to see what's happened
you can see that the memory usage is still going up by the time but right
after we stop the recursive call the garbage collector was able to collect
everything and freed up all the memory this because our X variable is not a
global anymore and once the recursive call stopped it lost all the references
to it and consider it as garbage so to sum up if your code involving with
allocating a global variable dynamically you need to explicitly clear them up or
they will continue to hold up the memory as long as to stay on a webpage and
please note that this is the only one example of how memory was leaked there
are some other type of leaks such as closure or circular references that can
cause the issue anyway I hope this video can give you the basic idea of the
memory leaks and how to find them. Please like or subscribe this helps. Red Stapler
peace!