这个 setTimeout 是否会造成任何内存泄漏?
这段代码会造成内存泄漏吗?或者代码有什么问题吗?
HTML:
<div id='info'></div>
Javascript:
var count = 0;
function KeepAlive()
{
count++;
$('#info').html(count);
var t=setTimeout(KeepAlive,1000);
}
KeepAlive();
在此处运行测试: http://jsfiddle.net/RjGav/
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/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可能应该使用 setInterval 来代替:
如果需要,您可以通过调用
clearInterval(KAinterval);
来取消它。You should probably use setInterval instead:
You can cancel it if you ever need to by calling
clearInterval(KAinterval);
.我认为这会泄漏,因为连续的引用从未发布。也就是说,第一次调用立即通过从自身内部引用该函数来创建一个闭包。当它再次调用自身时,新引用来自第一次迭代时创建的实例,因此第一个引用永远不会被释放。
你可以很容易地测试这个理论,方法是将间隔更改为非常小的值,然后观察 chrome 中的内存...
(编辑)用你的小提琴测试理论,实际上,我错了,它不会泄漏,至少在 Chrome 中。但这并不能保证其他浏览器(例如较旧的 IE)不擅长垃圾收集。
但无论它是否泄漏,都没有理由不使用 setInterval 来代替。
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.这不会造成泄漏,因为
KeepAlive
函数将及时完成,从而释放该函数中的所有变量。此外,在当前代码中,没有理由设置t
var,因为它未被使用。如果你想用它来取消你的事件,你应该在更高的范围内声明它。除此之外,我认为您的代码没有任何“错误”,但这实际上取决于您想要做什么。例如,如果您尝试将其用作精确计时器,它会比常规时钟慢。因此,您应该考虑设置页面加载日期并在需要时计算差异,或者按照 gddc 建议使用
setInterval
。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 thet
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.最好有像提到的 gddc 这样的
setInterval
方法。此外,最好将
$('#info')
存储在函数外部的变量中。查看 http://jsfiddle.net/RjGav/1/
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/