

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
- Related Questions & Answers
- Eradicating Memory Leaks in Javascript
- How can circular references cause memory leakage in JavaScript?
- Memory leaks in Java
- How can Detached DOM elements cause memory leak in JavaScript?
- Explain in detail about memory leaks in JavaScript?
- How can closures cause memory leak and how to prevent it?
- JavaScript Callbacks
- Can a microwave cause cancer?
- Node.js – Timers Module – Scheduling Timers
- Node.js – Timers Module – Cancelling Timers
- Timers in Arduino
- Callbacks in C
- Timers of 8051
- Timers in Arduino Uno
- PHP Callbacks/Callables