简体   繁体   English

javascript setInterval的内存泄漏

[英]Memory leak for javascript setInterval

Is there any difference between these 2 statements 这两个陈述之间有什么区别吗?

setInterval(animateImage, 1000);

or 

setInterval('animateImage()', 1000);

Will the second statement be interpreted by the browser js engine is any different way that could cause memory leak or performance issues. 浏览器js引擎是否会解释第二个语句是否会导致内存泄漏或性能问题。 Same is the case with the setTimeout() call. setTimeout()调用的情况也是如此。 The application makes use of 4 timer calls with 1-2 sec intervals. 该应用程序使用4个定时器调用,间隔为1-2秒。

The biggest difference is that the second statement will cause animateImage() to be evaluated in global scope. 最大的区别是第二个语句将导致animateImage()在全局范围内进行评估。

This can lead to problems if 这可能会导致问题

  • animateImage is not in global scope animateImage不在全局范围内
  • animateImage has to access variables that are not in global scope animateImage必须访问不在全局范围内的变量

Eg the following will not work: 例如,以下将不起作用

function foo() {
    var answer = 42;
    function bar() {
        alert(answer);
    }
    setTimeout('bar()', 1000);
}

foo();

Actually there is never a reason to use the second statement, so the question about memory leaks is not relevant anymore ;) 实际上没有理由使用第二个语句,因此关于内存泄漏的问题不再相关;)

And obviously, passing a direct reference to a function will be 'faster' than eval uating a string. 显然,传递对函数的直接引用将比eval字符串“更快”。

Use the first one. 使用第一个。 It makes debugging nicer since there's no eval'd code involved, it is faster and cleaner. 它使调试更好,因为没有涉及eval'd代码,它更快更干净。 Eval is evil and it's good to avoid it whenever possible. Eval是邪恶的,尽可能避免它是好的。

In case you ever need to pass an argument, use the following code: 如果您需要传递参数,请使用以下代码:

setInterval(function() {
    animateImage(...);
}, 1000);

The second statement will probably be slightly slower and use more memory, but it wouldn't be significant either way. 第二个语句可能会稍微慢一点并使用更多内存,但无论如何都不会很重要。 You should Use the first one regardless, because it's generally best to avoid using eval . 您应该使用第一个,因为通常最好避免使用eval

I don't think so. 我不这么认为。 You want to use callbacks to avoid memory leaks. 您希望使用回调来避免内存泄漏。

I recommend using it like so: 我建议像这样使用它:

setInterval(function(param1, param2){animateImage(param1, param2)}, 1000);

to pass parameters instead of passing them at the end 传递参数而不是在最后传递它们

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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