capdragon
capdragon

Reputation: 14899

Does a this setTimeout create any memory leaks?

Does this code create any memory leaks? Or is there anything wrong with the code?

HTML:

<div id='info'></div>

Javascript:

var count = 0;

function KeepAlive()
{
    count++;

    $('#info').html(count);
    var t=setTimeout(KeepAlive,1000);
}
KeepAlive();

Run a test here: http://jsfiddle.net/RjGav/

Upvotes: 2

Views: 2015

Answers (4)

g.d.d.c
g.d.d.c

Reputation: 47988

You should probably use setInterval instead:

var count = 0;

function KeepAlive() {
  $('#info').html(++count);
}

var KAinterval = setInterval(KeepAlive, 1000);

You can cancel it if you ever need to by calling clearInterval(KAinterval);.

Upvotes: 5

Briguy37
Briguy37

Reputation: 8402

This should not create a leak, because the KeepAlive function will complete in a timely manner and thus release all variables in that function. Also, in your current code, there is no reason to set the t var as it is unused. If you want to use it to cancel your event, you should declare it in a higher scope.

Other than that, I see nothing "wrong" with your code, but it really depends on what you are trying to do. For example, if you are trying to use this as a precise timer, it will be slower than a regular clock. Thus, you should either consider either setting the date on page load and calculating the difference when you need it or using setInterval as g.d.d.c suggested.

Upvotes: 3

sv_in
sv_in

Reputation: 14039

It is good to have setInterval method like g.d.d.c mentioned.
Moreover, it is better to store $('#info') in a variable outside the function.

Checkout http://jsfiddle.net/RjGav/1/

Upvotes: 2

Jamie Treworgy
Jamie Treworgy

Reputation: 24334

I think this will leak because the successive references are never released. That is, the first call immediately creates a closure by referencing the function from within itself. When it calls itself again, the new reference is from the instance created on the first iteration, so the first one could again never be released.

You could test this theory pretty easily by changing the interval to something very small and watch the memory in chrome...

(edit) theory tested with your fiddle, actually, I'm wrong it doesn't leak, at least in Chrome. But that's no guarantee some other browser (e.g. older IE) isn't as good at garbage collecting.

But whether or not it leaks, there's no reason not to use setInterval instead.

Upvotes: 5

Related Questions