John Hillegass John Hillegass - 4 years ago 120
Javascript Question

Does `document.getElementById` break the function?

So I am working on a pomodoro timer and can't figure out what I am doing wrong with my JS. Overview of the project is here : http://codepen.io/Ohillio/pen/wMoNWy

But the specific part of the code I am having issues with is :

// global variables
var min = 0;
var sec = 0;


function tick() {
alert("Counter Started");
sec = 59;
min--;
document.getElementById("timer").innerHTML = min + ":" + sec;
do {
sec--
document.getElementById("timer").innerHTML = min + ":" + sec;
setTimeout(donothing,500);
}
while (sec != 0);
}


The issue is that it seems like it ends the function after the first time through. I want the seconds to tick down to 0, but now it just evaluates to 58.

Does
document.getElementById
break the function ?

Answer Source

Using setInterval may be a better solution to what you're trying to do. It's going to be more accurate and easy to short circuit once you hit 0. Also, I prefer to keep the total time in seconds and only use minutes for display purposes. I've put together an example for you to review.

<script>
  var interval;
  var totalSeconds = 1500;

  function tick() {
    totalSeconds--;
    min = Math.floor(totalSeconds / 60);
    sec = totalSeconds % 60;
    document.getElementById('timer').innerHTML = min + ':' + sec;
    if (0 >= totalSeconds) {
        clearInterval(interval);
    }
  }
  interval = setInterval(tick, 1000);
</script>

Hope this helps and good luck!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download