简体   繁体   English

setTimeout导致内存泄漏

[英]setTimeout causing memory leak

var SetInactivityTimeOut = function () {
    try {
        var TimeoutInterval = parseInt(10, 10);

        var PreviousTimeStamp = Math.round(new Date().getHours() * 60 + new Date().getMinutes());

        if (TimeoutInterval === 0) return;

        TimeoutInterval = TimeoutInterval * 60 * 1000; //Converting to milisecond
        var TimeOutObj;
        if (TimeOutObj != null && TimeOutObj != undefined) {
            clearTimeout(TimeOutObj);
        }
        //Ti.API.info('TimeOutObj---'+TimeOutObj);
        TimeOutObj = setTimeout(function () {
            open the main page
        },TimeoutInterval);

    } catch (e) {
        error(e);
    }
}

This is the function i am using on every button click, once 10 minutes idle time has been finished, it opens back the index page. 这是我每次单击按钮都会使用的功能,空闲时间10分钟结束后,它将打开索引页面。 But when i try to login the application from there, its very slow and application gets hanged. 但是,当我尝试从那里登录应用程序时,它的速度非常慢,并且应用程序被挂起。

I am using this code in Mobile. 我在Mobile中使用此代码。 I just wanted to know is there any memory leak in the way the function is written. 我只是想知道函数编写方式中是否存在任何内存泄漏。

As you have your function at the moment, TimeOutObj is being declared in the same function that you check to see if it exists, it will always exist but will always be undefined at the point where you are checking to see if it is a timeout id, so you will never actually clear the timeout. 由于您目前拥有函数,因此TimeOutObj会在您检查其是否存在的同一函数中声明,该函数将始终存在,但在您检查其是否为超时id时将始终undefined ,因此您永远不会真正清除超时。

By wrapping the majority of your SetInteractivityTimeout function in a closure, you can declare the TimeOutObj outside of the scope of the actual handling function, so it will maintain its value each time you call the SetInactivityTimeout function. 通过将大多数SetInteractivityTimeout函数包装在一个闭包中,可以在实际处理函数的范围之外声明TimeOutObj ,因此每次调用SetInactivityTimeout函数时,它将保持其值。

var SetInactivityTimeOut = (function () {
   var TimeOutObj;
   var TimeoutInterval = 10 * 60 * 1000; //Converting to milisecond

   return function() {
     if (TimeOutObj) {
       clearTimeout(TimeOutObj);
     }

     TimeOutObj = setTimeout(function () {
       // open the main page
     }, TimeoutInterval);
   }
 }());

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

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