简体   繁体   中英

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/

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); .

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 (eg older IE) isn't as good at garbage collecting.

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

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 gddc suggested.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM