Why two timers starts javascript issue, when timer start & I press some another timer at that time both timers are running

Viewed 16

So here I create one contdown web application using HTML, CSS and JS and now I am stuck that how to reset the intervel time out function when click on some another button.

index.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Countdown Timer</title>
  <link href='https://fonts.googleapis.com/css?family=Inconsolata' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <div class="timer">
    <div class="timer__controls">
      <button data-time="20" value="20" class="timer__button">20 Secs</button>
      <button data-time="300" value="300" class="timer__button">Work 5</button>
      <button data-time="900"  value="900" class="timer__button">Quick 15</button>
      <button data-time="1200" value="1200" class="timer__button">Snack 20</button>
      <button data-time="3600" value="3600" class="timer__button">Lunch Break</button>
      <form name="customForm" id="custom">
        <input  id="customMin" placeholder="Enter Minutes" >
      </form>
    </div>
    <div class="display">
      <h1 id="display__time-left">00:00</h1>
      <p id="display__end-time">Be Back At 00.00</p>
    </div>
  </div>

  <script src="script.js"></script>
</body>

</html>

Here in the script.js file as I mantioned , javascript uses the setTimeout feature of javascript to build one countdown web application and now when in a output browser I press Lunch time button it will show the timer for the next 1Hour and than it is stop in 00:00... as I want if one timer is running and I press some another button or some custom input for taking seconds than at that time both timers are running. So please provide the solution that what I have to do. scripts.js

let allButtons = document.querySelectorAll(".timer__button");
let valueOfTime;
for (var i = 0; i < allButtons.length; i++) {
  allButtons[i].addEventListener("click", function () {
    valueOfTime = this.value;
    BackAt();
  });
}

setInterval(function () {
  var minutes = Math.floor(valueOfTime / 60);
  var seconds = valueOfTime % 60;
  if (valueOfTime > 0) {
    document.getElementById("display__time-left").innerHTML = minutes + ":" + seconds;
  }
  else{
    document.getElementById("display__time-left").innerHTML = "00:00"; 
  }
  valueOfTime--;
}, 1000);

document.getElementById("customMin")
  .addEventListener("keypress", function (event) {
    if (event.key === "Enter") {
      event.preventDefault();
      let inputMin = document.getElementById("customMin").value *60;
      inputBackAt(inputMin);
      setInterval(function () {
        var minutes = Math.floor((inputMin / 60));
        var seconds = inputMin % 60;
        if (inputMin > 0) {
          document.getElementById("display__time-left").innerHTML =
            minutes + ":" + seconds;
        }
        inputMin--;
      }, 1000);
    }
  });

function BackAt() {
  var minutes = Math.floor(valueOfTime / 60);
  let currentHours=new Date().getHours();
  let currentMin= new Date().getMinutes();
  let x = currentMin + minutes;
  if (x > 59) {
    let remainingMinutes = x-60;
 document.getElementById('display__end-time').innerHTML= `Be Back At ${currentHours+1} : ${remainingMinutes}`;
  }
  else{
    let remainingMin  =currentMin+minutes;
    document.getElementById('display__end-time').innerHTML= `Be Back At ${currentHours} : ${remainingMin}`;
  }
}

function inputBackAt(inputMin){
  var minutes = Math.floor((inputMin/ 60));
  let currentHours=new Date().getHours();
  let currentMin= new Date().getMinutes();
  let y = currentMin + minutes;
  if (y> 59) {
    let remainingMinutes = y-60;
 document.getElementById('display__end-time').innerHTML= `Be Back At ${currentHours+1} : ${remainingMinutes}`;
  }
  else{
    let remainingMin  =currentMin+minutes;
    document.getElementById('display__end-time').innerHTML= `Be Back At ${currentHours} : ${remainingMin}`;
  }
}

when I click on one button and the timer is running , after some time when I press another button to start the new timer at that time both previous and current timer are running.

1 Answers

This defines a Timer class that instantiates an independent timer, then create multiple copies of it. The time for each timer as well as how long a "tick" can both be supplied as arguments to the constructor. Each time the timer ticks it can call the optional updateCallback to notify you.

The example starts three timers, one for three "minutes" (a minute it actually set to 3 seconds) that ticks every second, one for six "minutes" that ticks every 500 milliseconds and one for 15 "minutes" that ticks every 200 milliseconds.

Timer (seconds, period, update, reset)

  • seconds: How many seconds the timer should last
  • period: How long a "tick" is
  • update: [Optional] A callback that is called after every tick
  • reset: [Optional] A callback back that will be called when the timer ends (or if Timer.reset() is called)

let oneSecond = 500; // this should be 1000, set to 500 for the example
let oneMinute = 3;   // this should be 60, set to 3 for the example

let sessionTime = 3;

function Timer(seconds, period, updateCallback, resetCallback) {
    this.s = seconds;
    this.p = period || oneSecond;
    this.update = updateCallback || Function.prototype; // Use NOOP function as default
    this.callback = resetCallback || Function.prototype; // Use NOOP function as default

    this.reset = function() {
      this.intervalId = clearInterval(this.intervalId)
      this.callback()
    }
    this.start = function() { this.update(this.s); this.intervalId = setInterval(this.timer.bind(this), [ this.p ]) }
    this.timer = function() { if (--this.s <= 0) this.reset(); this.update(this.s) }
}

function setTimeLeft(sec, id) {
  document.getElementById(id || 'time-left').textContent = `${(''+ ~~(sec / oneMinute)).padStart(2, '0')}:${(''+ sec % oneMinute).padStart(2, '0')}`;
}

document.addEventListener("DOMContentLoaded", function() {
  new Timer(sessionTime * oneMinute, 1000, setTimeLeft, () => console.log('check 1000ms')).start()
  new Timer(6 * oneMinute, 500, (s) => { setTimeLeft(s, 'time-left2')}, () => console.log('check 500ms')).start()
  new Timer(15 * oneMinute, 200, (s) => { setTimeLeft(s, 'time-left3')}, () => console.log('check 200ms')).start()
})
<span id='time-left'></span><br />
<span id='time-left2'></span><br />
<span id='time-left3'></span>

Related