A good example of a js memory leak

  • 2020-03-30 00:46:47
  • OfStack

I changed someone else's example to make it more compact! To paraphrase someone else, when a DOM object contains a reference to a Js object (such as an Event Handler), and the Js object holds a reference to the DOM object, a circular reference is made, and memory leaks occur under ie. Click "run code" and open the task manager to see the memory changes. Testing under ie8 and ff respectively, the gap need not say much.

Run the code


<html>
  <head>
    <title>Memory leak</title>
    <style>
     body{
       padding: 10px;
     }
    </style>
  </head>
  <body>
  </body>
  <script>
    var q = [];
    var n = 0;
    setInterval(function(){
      q.push(makeSpan());
      if(q.length>=10){
        var s = q.shift();
        if(s){
          s.parentNode.removeChild(s);
        }
      }
      n++;
    },10);

    function makeSpan(){
      var s = document.createElement("span");
      document.body.appendChild(s);
      var t=document.createTextNode("*** " + n + " ***");
      s.appendChild(t);
      s.onclick=function(e){
                s.style.backgroundColor="red";
                alert(n);
            };
            return s;
    };
  </script>
</html>

So what's the solution under ie?

When deleting a node, manually break the circular reference and change the setInterval code inside a bit:


setInterval(function(){
  q.push(makeSpan());
  if(q.length>=10){
    var s = q.shift();
    if(s){
     s.onclick = null;//Here's the key
      s.parentNode.removeChild(s);
    }
  }
  n++;
},10);


Related articles: