Advertisement
kstoyanov

04. Stopwatch

Oct 1st, 2020
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function stopwatch() {
  2.   const currentTime = document.querySelector('#time');
  3.   const startButton = document.querySelector('#startBtn');
  4.   const stopButton = document.querySelector('#stopBtn');
  5.   let time = 0;
  6.   let intervalId;
  7.  
  8.   const formatTime = (timeValue) => {
  9.     const min = Math.floor(timeValue / 60);
  10.     const sec = timeValue % 60;
  11.     return `${(`0${min}`).slice(-2)}:${(`0${sec}`).slice(-2)}`;
  12.   };
  13.  
  14.   const startButtonHandler = () => {
  15.     time = 0;
  16.     currentTime.innerText = formatTime(0);
  17.     stopButton.removeAttribute('disabled');
  18.     startButton.setAttribute('disabled', true);
  19.  
  20.     intervalId = setInterval(() => {
  21.       time++;
  22.       currentTime.innerText = formatTime(time);
  23.     }, 1000);
  24.   };
  25.  
  26.   const stopButtonHandler = () => {
  27.     stopButton.setAttribute('disabled', true);
  28.     startButton.removeAttribute('disabled');
  29.     clearInterval(intervalId);
  30.   };
  31.  
  32.   startButton.addEventListener('click', startButtonHandler);
  33.  
  34.   stopButton.addEventListener('click', stopButtonHandler);
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement