简体   繁体   中英

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. But when i try to login the application from there, its very slow and application gets hanged.

I am using this code in 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.

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.

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

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