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

JavascriptObject Oriented ProgrammingProgramming

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.


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.

   for (var i = 0; i < 100000; i++) {
   var tiedObject = {
   callAgain: function() {
      var text = this;
      var value = setTimeout(function() {
      }, 100000);
   tiedObject = null;

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. 

Published on 03-Jun-2019 16:29:47