0

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();
Satpal
134k13 gold badges168 silver badges171 bronze badges
asked Mar 24, 2017 at 12:58
3
  • I see stackoverflow :) Commented Mar 24, 2017 at 13:00
  • setInterval repeats automatically, you don't have to re-call it. You're confusing it with setTimeout. Commented Mar 24, 2017 at 13:02
  • Well you are recursively setting up interval which in turn calls updateTime which again sets up Interval to call updateTime and this happens again and again until you run out of memory Commented Mar 24, 2017 at 13:03

1 Answer 1

3

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); 
answered Mar 24, 2017 at 13:02
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.