Timer to begin on the start date entered by user

Viewed 54

I have a working timer but the idea is that the timer does not start until the date and time the user enters comes. for example, startdate: 1/15/2021 time: 1:15pm
enddate: 1/15/2021 time: 1:18pm if today is the 14th and I entered this information today (14th), the timer shouldn't start until the 15th at exactly 1:15 pm. I used the setTimeout function where I passed in the start

function myfunction(){

// Set the date we're counting down to

var enddate= document.getElementById("end_date").value;
var startdate = document.getElementById("start_date").value;

if(startdate == '' || enddate == ''){
return
}

enddate = new Date(enddate)
startdate = new Date(startdate)
var distance = enddate - startdate;



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

  // Get start date and time
  //var startdate = document.getElementById("start_date").innerHTML;
    
  // Find the distance between startdate and the end date
  //var distance = enddate - startdate;
 // console.log(distance)
    
  // Time calculations for days, hours, minutes and seconds
  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  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);
    
  // Output the result in an element with id="demo"
  document.getElementById("demo").innerHTML = days + "d " + hours + "h "
  + minutes + "m " + seconds + "s ";
  
  distance = distance - 1000;
    
  // If the count down is over, write some text 
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }

   if (minutes == 20) {
document.getElementById("demo").innerHTML = "Your Heart rate and blood pressure will drop";}
}, 1000);

}

var y = setTimeout(function(){
alert("tryout starts now")
}, startdate);
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
p {
  text-align: center;
  font-size: 60px;
  margin-top: 0px;
}
</style>
</head>
<body>




<input type="datetime-local" id="start_date"  onchange='myfunction()' placeholder="Start Date" />
 - 
<input type="datetime-local" id="end_date" onchange='myfunction()' placeholder="End Date" />
<p id="demo"></p>
</body>
</html>

date to indicate that that's when it should start but it's not working. Any other approach/idea will be welcomed.

0 Answers
Related