DIES
DIES

Reputation: 349

JS setInterval() mem leak

I know it's bunch of questions and answers here about this problem, but I don't know if it's realy applies to mine case.

I have a time script, with setInterval function. It works fine, for first minutes, but then in chrome/opera task manager I see that tab with this script running going from 40mb to 2-3gb! It's insane, and I don't know how to fix that. Only if rewrite all script in a different way.

Script:

function checkTime(i) {
    return (i < 10) ? "0" + i : i;
};

function calcTime(city, offset) {
    d = new Date();
    utc = d.getTime() + (d.getTimezoneOffset() * 60000);
    nd = new Date(utc + (3600000*offset)),
        h = checkTime(nd.getHours()),
        m = checkTime(nd.getMinutes()),
        s = checkTime(nd.getSeconds());
    return nd.toLocaleString();
};

function updateTime() {
    if (document.getElementById('timeMoscow')) {
        calcTime('Moscow', '+3');
        document.getElementById('timeMoscow').innerHTML = h + ":" + m /*+ ":" + s*/;
    }
    if (document.getElementById('timeKiev')) {
        calcTime('Kiev', '+2');
        document.getElementById('timeKiev').innerHTML = h + ":" + m /*+ ":" + s*/;
    } else 
    if (document.getElementById('timeAstana')) {
        calcTime('Astana', '+6');
        document.getElementById('timeAstana').innerHTML = h + ":" + m /*+ ":" + s*/;
    }
    if (document.getElementById('timeNewYork')) {
        calcTime('NewYork', '-4');
        document.getElementById('timeNewYork').innerHTML = h + ":" + m /*+ ":" + s*/;
    }
    setInterval(updateTime, 500); //Problem
}

updateTime();

Upvotes: 0

Views: 1039

Answers (1)

Satpal
Satpal

Reputation: 133403

You are recursively invoking updateTime function that using setInterval which is repeatedly calls updateTime. Remove setInterval() call from the method and invoke it like.

function updateTime() {
    //You rest of code
}

setInterval(updateTime, 500); 

Upvotes: 3

Related Questions