Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs setTimeout memory leak?

Tags:

node.js

memory

v0.10.4

Here's the simple loop that results in an ever-increasing memory usage:

function redx(){
      setTimeout(function(){ redx() },1000);
      console.log('loop');
}

redx();

What am I doing wrong ??

EDIT

OK, just tried the suggestion to reference the timeout object in the scope and it seems that garbage collection does kick in after about 40 seconds, here's abbreviated logs from TOP:

3941 root 20 0 32944 7284 4084 S 4.587 3.406 0:01.32 node
3941 root 20 0 32944 7460 4084 S 2.948 3.489 0:01.59 node
3941 root 20 0 32944 7516 4084 S 2.948 3.515 0:01.68 node
3941 root 20 0 33968 8400 4112 S 2.948 3.928 0:02.15 node
3941 root 20 0 33968 8920 4112 S 3.275 4.171 0:02.98 node
3941 root 20 0 33968 8964 4112 S 2.948 4.192 0:03.07 node
3941 root 20 0 33968 9212 4112 S 2.953 4.308 0:03.16 node
3941 root 20 0 33968 9212 4112 S 2.953 4.308 0:03.25 node
3941 root 20 0 33968 9212 4112 S 3.276 4.308 0:03.35 node
3941 root 20 0 33968 9212 4112 S 2.950 4.308 0:03.44 node

like image 899
crankshaft Avatar asked Apr 18 '13 00:04

crankshaft


People also ask

Can setTimeout cause a memory leak?

The setTimeout function executes when the given time is elapsed, whereas setInterval executes repeatedly for the given time interval. These timers are the most common cause of memory leaks.

How do I resolve a memory leak issue in Node JS?

A quick way to fix Node. js memory leaks in the short term is to restart the app. Make sure to do this first and then dedicate the time to seek out the root cause of the memory leak.

Does console log consume memory?

console. log() causes memory leaks but only when the console is opened. Normally users do not open the console. So it is totally safe to print any huge objects to the console.


1 Answers

No idea why but apparently if you reference the timeout object in the scope of the function nodejs will do the garbage collect that correctly.

function redx(){
      var t = setTimeout(function(){ redx() },50);
      console.log('hi');
}

redx();
like image 175
Tommaso Barbugli Avatar answered Sep 19 '22 06:09

Tommaso Barbugli