Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding start, stop, and reset buttons for a timer

Tags:

javascript

I'm making a timer and have it working already one load. I want to add a start, stop, and reset button to it. This is my code as is atm.

    (function() {
         "use strict";
         var secondsLabel = document.getElementById('seconds'),
         minutesLabel = document.getElementById('minutes'),
         hoursLabel = document.getElementById('hours'),
         totalSeconds = 0,
         startButton = document.getElementById('start'),
         resetButton = document.getElementById('reset'),
         onOff = 0; 
         startButton.onclick = function() {
         onOff = 1;
     };
     resetButton.onclick = function() {
         totalSeconds = 0;
         onOff = 0;
     };

     if ( onOff == 1 ) {
         setInterval( setTime, 1000 );
         function setTime() {
         totalSeconds++;
         secondsLabel.innerHTML = pad( totalSeconds % 60 );
         minutesLabel.innerHTML = pad( parseInt( totalSeconds / 60 ) );
         hoursLabel.innerHTML = pad( parseInt( totalSeconds / 3600 ) )
     }
     function pad( val ) {
         var valString = val + "";
         if( valString.length < 2 ) {
            return "0" + valString;
         } else {
            return valString;
         }
     }
   }

 })();

The buttons are not working atm however. I'm not sure if this the best solution for the goal as well, so suggestions are welcome.

like image 781
Patrick Avatar asked Mar 22 '23 20:03

Patrick


1 Answers

(function() {
  "use strict";
  var secondsLabel = document.getElementById('seconds'), minutesLabel = document.getElementById('minutes'), hoursLabel = document
      .getElementById('hours'), totalSeconds = 0, startButton = document.getElementById('start'), stopButton = document.getElementById('stop'), resetButton = document
      .getElementById('reset'), timer = null;

  startButton.onclick = function() {
    if (!timer) {
      timer = setInterval(setTime, 1000);
    }
  };

  stopButton.onclick = function() {
    if (timer) {
      clearInterval(timer);
      timer = null;
    }
  };

  resetButton.onclick = function() {
    if (timer) {
      totalSeconds = 0;
      stop();
    }
  };

  function setTime() {
    totalSeconds++;
    secondsLabel.innerHTML = pad(totalSeconds % 60);
    minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
    hoursLabel.innerHTML = pad(parseInt(totalSeconds / 3600))
  }

  function pad(val) {
    var valString = val + "";
    if (valString.length < 2) {
      return "0" + valString;
    } else {
      return valString;
    }
  }

})();
like image 111
closure Avatar answered Apr 05 '23 21:04

closure