javascript setInterval 的内存泄漏 [英] Memory leak for javascript setInterval

查看:140
本文介绍了javascript setInterval 的内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两种说法有什么区别

setInterval(animateImage, 1000);

or 

setInterval('animateImage()', 1000);

第二个语句是否会被浏览器 js 引擎解释为可能导致内存泄漏或性能问题的任何不同方式.setTimeout() 调用的情况也是如此.该应用程序使用 4 个定时器调用,间隔为 1-2 秒.

Will the second statement be interpreted by the browser js engine is any different way that could cause memory leak or performance issues. Same is the case with the setTimeout() call. The application makes use of 4 timer calls with 1-2 sec intervals.

推荐答案

最大的不同是第二条语句会导致 animateImage() 在全局范围内被求值.

The biggest difference is that the second statement will cause animateImage() to be evaluated in global scope.

这可能会导致问题

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

例如以下将不起作用:

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

显然,传递对函数的直接引用将比eval使用字符串更快".

And obviously, passing a direct reference to a function will be 'faster' than evaluating a string.

这篇关于javascript setInterval 的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆