How can Forgotten timers or callbacks cause memory leaks in JavaScript?


Forgotten timers/callbacks

There are two timing events in javascript namely setTimeout() and setInterval(). The former executes a function after waiting a specified number of milliseconds, whereas the latter executes a function periodically(repeats for every certain interval of time).

When any object is tied to a timer callback, it will not be released until the timeout happens. In this scenario timer resets itself and runs forever till the completion of timeout there by disallowing garbage collector to remove the memory.These timers are most frequent cause of memory leaks in javascript.

Example

In the following example, the timer callback and its tied object(tiedObject) will not be released until the timeout finishes. In the mean time the timer resets itself and runs forever and therefore its memory space will never be collected even there is no reference to the original object.

<html>
<body>
<script>
   for (var i = 0; i < 100000; i++) {
   var tiedObject = {
   callAgain: function() {
      var text = this;
      var value = setTimeout(function() {
      text.callAgain();
      }, 100000);
   }
   }
   tiedObject.callAgain();
   tiedObject = null;
   }
</script>
</body>>
</html>

Avoiding memory leaks

1.To avoid leakage provide references inside setInterval()/setTimeout() such that functions are needed to be executed before they can be garbage collected.

2.Make a direct call to remove functions once they are no longer needed.

Except for old browsers such as IE, most of the modern browsers such as chrome etc. will not face these kind of problems. More importantly libraries like jquery handle internally to make sure that no leakage problems be produced. 


Updated on: 30-Jul-2019

525 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements