Edwin Reynoso
Edwin Reynoso

Reputation: 1531

Why does this function take up a lot of memory overtime

I'm trying to understand why does this small function after a reaches around almost 200,000 under about:memory tab it says that the devtools's total memory is: 1079408k? can someone explain why?

var a = 0;
(function loop(){
 a++;
 console.count();
 call = setTimeout(loop);
})()

Upvotes: 0

Views: 96

Answers (2)

Wold
Wold

Reputation: 972

The function itself continues on infinitely in a loop.

call = setTimeout(loop);

Just calls the function again, which calls that line again. There is no return statement, so the recursion never stops and it loops on infinitely.

As pointed out in the comments, it isn't necessarily recursive since there is no stack building up. The memory is building up because as dystroy pointed out

console.count();

causes the console to count the amount of times that function is called, and since it is being called infinitely, the memory is quickly filled with thousands of lines console.count() output.

Upvotes: 0

Denys Séguret
Denys Séguret

Reputation: 382130

There was speculation in comments but nobody checked, so I did it :

When you remove the console.count(), the memory stops growing. What you saw was just the console growing : those lines must be stored somewhere.

Upvotes: 6

Related Questions