0
  1. Im creating a countdown timer which starts at 3mins and 30secs.
  2. When the timer reaches 0 the initial 3:30 timer will be repeated.
  3. This happens until the user presses a button, which will add 1:45 to the timer and pause the timer until the user decides to resume the timer from the new value. Eg ( 3:30 + 1:45 = 5:15).

Now I have got the first 2 step to work with my current code, but I'm having a lot of issues with the 3rd part. Once the user clicks the add 1.45 button the count works, but only up until a certain point. After this point it will start to display a negative integer.

I'm sure there is an easier way to write this code. I have really overcomplicated this. Any suggestions would be appreciated.

//Define vars to hold time values
let startingMins = 3.5;
let time = startingMins * 60;

//define var to hold stopwatch status
let status = "stopped";
//define var to holds current timer
let storeTime = null; 
//define Number of sets
let setNum = 1;

//Stop watch function (logic to determin when to decrement each value)
function stopwatch () {
    minutes = Math.floor(time / 60);
    let seconds = time % 60;
    seconds = seconds < 10 ? '0' + seconds : seconds;
    storeTimer = minutes + ":" + seconds; //Store time in var
    storeTime = minutes + "." + seconds; //Store time in var

    //Display updated time values to user
    document.getElementById("display").innerHTML = storeTimer;
    time--;

    // When timer reachers 0 secs the inital 3:30 countdown will begin again.
    if (time <= 0) {
        startingMins = 3.5;
        time = startingMins * 60;
        minutes = Math.floor(time / 60);
        seconds = time % 60;
        seconds = seconds < 10 ? '0' + seconds : seconds;
        setNum++;
        //console.log(setNum);
    }
}


function StartStop() {
    if(status === "stopped") {
        //start watch
        interval = window.setInterval(stopwatch, 100);
        var startButton = document.getElementById("start");
        document.getElementById("start").innerHTML = "Pauce";
        //startButton.style.display = "none"
        status = "start";
        //console.log(time);
    }
    else { 
        window.clearInterval(interval);
        document.getElementById("start").innerHTML = "Start";
        status = "stopped";
        console.log(storeTime);
    }
}

function pauceAdd () {

    if(status === "stopped") {
        //start watch
        interval = window.setInterval(stopwatch, 1000);
        var zukButton = document.getElementById("pauceAdd");
        status = "start";
    }
    else { 
        window.clearInterval(interval);
        status = "stopped";
        console.log("store time " + storeTime);
        let time = +storeTime + +1.45; //store time is 3.30 adding 4.75
        console.log("store time2 " + time); // correct result 4.75 
        minutes = Math.floor(time);/// convert time from Mins (4.75) to seconds (475)
        let seconds = time % 60; // 5
        
        if (seconds < 60 ) { // if the Stored time is greater than 60 secs add 1 minute to the timer
            minutes++;
            seconds = seconds * 100; 
            console.log("secs updated = " + seconds ); // seconds updated (475)
            if (seconds <= 460) { 
                seconds = Math.floor(seconds - 460); 
                console.log("seconds 2 == " + seconds)
            }
            else if (seconds > -60) { // Stuck here
                seconds = seconds + 60;// Stuck here
            }// Stuck here
            else {
                seconds = Math.floor(seconds - 460);
                console.log("seconds 2 = " + seconds)
            }
        }
        if (seconds < 1) {
            seconds = seconds + 60;
            minutes = minutes - 1;
        }

        seconds = seconds < 10 ? + seconds : seconds;
        console.log("mins updated = " + minutes + "__________________________-");

        //Display updated time values to user
        document.getElementById("display").innerHTML = minutes + ":" + seconds;
    }
}

function reset () {
    //window.clearInterval(storeTime);
    window.clearInterval(interval);
    startingMins = 3.5;
    time = startingMins * 60;
    minutes = Math.floor(time / 60);
    seconds = time % 60;
    seconds = seconds < 10 ? '0' + seconds : seconds;
    status = "stopped";
    setNum = 1;
    var startButton = document.getElementById("start");
    startButton.style.display = "inline-block";
    document.getElementById("display").innerHTML = "3:30";
    document.getElementById("start").innerHTML = "Start";
}
1
  • At minimum, it looks like you're storing time as minutes.seconds and then, later, trying to use that like it was an actual number. 1 minute 54 seconds is 1.9 minutes but the way you're converting it, you get 1.54 minutes. Commented Nov 22, 2020 at 22:40

1 Answer 1

1

I might have taken the requirements a bit too literally:

  1. Im creating a countdown timer which starts at 3mins and 30secs.
  2. When the timer reaches 0 the initial 3:30 timer will be repeated.
  3. This happens until the user presses a button, which will add 1:45 to the timer and pause the timer until the user decides to resume the timer from the new value. Eg ( 3:30 + 1:45 = 5:15).

There's a trick to countdown timers. You have to use timestamps to find out how much time ACTUALLY elapsed. You can't trust that your interval will fire exactly every second. In fact, it almost always fires a bit later (in my tests, about 2-3 milliseconds, but I was logging to the console as well, so that might have skewed the test).

let interval, timestamp;
let countdown = 210000;

document.addEventListener("DOMContentLoaded", () => {
  document
    .querySelector("button")
    .addEventListener("click", (event) => toggleState(event.target));
});

function toggleState({ dataset }) {
  timestamp = Date.now();
  if (dataset.state == "running") {
    clearInterval(interval);
    countdown += 105000;
    updateDisplay(dataset, "paused");
  } else {
    interval = setInterval(() => updateCountdown(dataset), 100);
    updateDisplay(dataset, "running");
  }
}

function updateCountdown(dataset) {
  const now = Date.now();
  countdown -= now - timestamp;
  if (countdown <= 0) countdown = 210000;
  timestamp = now;
  updateDisplay(dataset, "running");
}

function updateDisplay(dataset, label) {
  dataset.state = label;
  dataset.time = `(${new Date(countdown).toISOString().slice(14, 19)})`;
}
button::before {
  content: attr(data-state);
}

button::after {
  content: attr(data-time);
  padding-left: 0.5em;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet" />
<button data-state="stopped" data-time="(03:30)"></button>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.