-1

I'm currently working on a flight entertainment system project that contains a timer that specifies how long is left in the flight. I want to write a function that specifies a certain time such as "3 hours 20mins" and countdown from that. I need it to run from when I open the page and reset it automatically whenever it hits 0. Its really just there for aesthetics. It can be seen in the top right of the image I attached.

Right now I just have regular text in my HTML file :

<div class="flighttime">
            3H 20M
          </div>

enter image description here

1 Answers1

0

function addTime(hours, minutes, date = new Date()) {
  date.setTime(date.getTime() + hours * 3600000 + minutes * 60000);

  return date.getTime();
}

const time = document.getElementById('time');
const [hours, minutes] = time.textContent.split(' ').map(i => parseFloat(i));

console.log(hours, minutes)

var countDownDate = addTime(hours, minutes)

// Update the count down every 1 second
var x = setInterval(function() {

  // Get today's date and time
  var now = new Date().getTime();

  // Find the distance between now and the count down date
  var distance = countDownDate - now;

  // Time calculations for days, hours, minutes and seconds
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);

  // Display the result in the element with id="demo"
  time.innerHTML = hours + "H "
  + minutes + "M " + seconds + "S";

  // If the count down is finished, write some text
  if (distance < 0) {
    clearInterval(x);
    time.innerHTML = "EXPIRED";
  }
}, 1000);
<div id="time">3H 30M</div>
Mina
  • 14,386
  • 3
  • 13
  • 26