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 :

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;
document.getElementById("timer").innerHTML = min + ":" + sec;
do {
document.getElementById("timer").innerHTML = min + ":" + sec;
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.

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.

  var interval;
  var totalSeconds = 1500;

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

Hope this helps and good luck!

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