0

I am very new to JS and I've set myself a goal of creating a simple countdown timer. Its based around work and when to come off breaks, lunch ect.

The issue I am having is that 15mins (15000ms) is equal to 9 mins within my script. I cannot for the life of me work out why or where this conversion is happening.

I apologise for the code format, I am a noob and only started JS last week.

    function timer(number){

  //conversion from seconds to milliseconds
  number *= 1000;

  //when to come back from break
  let countDownDate = new Date();
  countDownDate.setSeconds(countDownDate.getSeconds() + number);

  setInterval(updateTime, 1000);

    function updateTime() {

//calculate the 'now' time and the 'target' time and divide it 
let now = new Date().getTime();
let distance = countDownDate - now;

let days = Math.floor(distance / (1000 * 60 * 60 * 24));
let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
let seconds = Math.floor((distance % (1000 * 60)) / 1000);

 if (distance < 0) {
     minutes += 1;}

 //display data on P tag
 document.getElementsByClassName('countdown')[0].innerHTML = minutes + "m " + seconds + "s ";
 document.getElementsByClassName('return-time')[0].innerHTML = countDownDate.getHours() + ":" + countDownDate.getMinutes() + ":" + countDownDate.getSeconds();

}};

//buttons on nav bar add time to timer
const keys = document.querySelector('nav');
keys.addEventListener('click', (event) => {
  const { target } = event;
  if (!target.matches('li, a, input')) {
    return;
  }

  if (target.classList.contains('breaks')) {
    timer(15);
    return;
  }

  if (target.classList.contains('lunch')) {
    timer(30);
    return;
  }

  if (target.classList.contains('personal')) {
    timer(10);
    return;
  }

  console.log('null', target.value);
});
Tom TK
  • 65
  • 9
  • 3
    *15mins (15000ms)"* -> 15000ms != 15 minutes. 15 minutes is equal to 900000ms – Calvin Nunes Jan 08 '20 at 19:37
  • JavaScript time is [notoriously inaccurate](https://stackoverflow.com/questions/29971898/how-to-create-an-accurate-timer-in-javascript). – isherwood Jan 08 '20 at 19:37
  • "*15mins (15000ms)*"??? 1ms = 1/1000th of a second, so 15000ms = 15 seconds. 9 minutes would be `9 * 60 * 1000 = 540 000 ms`. While 15 minutes are `15 * 60 * 1000 = 900 000 ms`. – VLAZ Jan 08 '20 at 19:42
  • I'm an idiot, I'll fix that! – Tom TK Jan 08 '20 at 19:56

0 Answers0