0

I use JavaScript to display a binary clock on a website. When the site is first loaded, the clock needs to be set to the right time and then updated.

What is the right way to get this behaviour? Right now I have a var that is checked on every update and is set to false after the first run.

Would it be better to copy the function, remove the conditions and have it call the other function?

This is the function:

time.firstRun = true;

function updateBinaryClock() {
var now = moment().toObject();

var bin;
if (time.showClockWithSeconds) {
    bin = toSixBit(now.seconds.toString(2));
    setColor(".binSec", bin);
}
if (now.seconds == 0 || time.firstRun) {
    bin = toSixBit(now.minutes.toString(2));
    setColor(".binMin", bin);
}
if (now.minutes == 0 || time.firstRun) {
    bin = toSixBit(now.hours.toString(2));
    setColor(".binHour", bin);
}
if (time.firstRun) {
    time.firstRun = false;
}

setTimeout(updateBinaryClock, 0.1 * 1000);
}
w_n
  • 345
  • 3
  • 7
  • I would add a parameter: `function updateBinaryClock(firstRun){...}`, and call it like that for the first time: `updateBinaryClock(true);`. Then, when it gets called by `setTimeout`, this parameter won't be there anymore. – blex Oct 15 '16 at 21:37

2 Answers2

2

Your function will saturate your ram soon, because you forgot to clear timeout on every function execution. You could use setInterval instead of setTimeout:

function updateBinaryClock() {
    aux_updateBinaryClock(true);
    setInterval(aux_updateBinaryClock, 100); // 0.1*1000
}

function aux_updateBinaryClock(isFirstRun) {
  var now = moment().toObject(),
      bin;

  if (time.showClockWithSeconds) {
      bin = toSixBit(now.seconds.toString(2));
      setColor(".binSec", bin);
  }
  if (now.seconds === 0 || isFirstRun) {
      bin = toSixBit(now.minutes.toString(2));
      setColor(".binMin", bin);
  }
  if (now.minutes === 0 || isFirstRun) {
      bin = toSixBit(now.hours.toString(2));
      setColor(".binHour", bin);
  }

}

updateBinaryClock();

Also note that setInterval and setTimeout are inaccurate, there are many more accurate implementations of setInterval and setTimeout (es. this or this)

Community
  • 1
  • 1
Gab
  • 491
  • 3
  • 6
  • Thank you, that was very helpful. I already noticed a memory leak, but dind't know where to look for it. – w_n Oct 16 '16 at 12:19
0

What I would do is separate it into 2 functions.

function initBinaryClock() {

}
function updateBinaryClock() {

  requestAnimationFrame(updateBinaryClock);
}

window.addEventListener("load", function loader(){
  window.removeEventListener("load", loader, false);
  initBinaryClock();
  updateBinaryClock();
}, false);
pgarciacamou
  • 1,602
  • 22
  • 40