Attempting to make a countdown clock where the user puts in the name of the event and the date and the function writes to the document that clock with the name of the event. I can get it to run once with the information but not continually update. I’ve kept it in the same file as the GET method seemed to cause some problems. This was to essentialize this issue. I’ve tried both setInterval and setTimeout.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Event Countdown Form</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<form>
<br>
<label for="name"></label>
<br>
<input type="text" id="name" name="name">
<br><br>
<label for="date"></label>
<br>
<input type="date" id="date" name="date">
<br><br>
<button onClick="countdown()">Submit</button>
</form>
<script>
function countdown () {
const newName = document.getElementById("name").value;
const newDate = document.getElementById("date").value;
const birthday = new Date(newDate);
//initializing the values of days, hours, minutes, seconds in milliseconds
const second = 1000;
const minute = second * 60;
const hour = minute * 60;
const day = hour * 24;
//calculating time left to the event
const today = new Date();
const timespan = birthday - today;
const days = Math.floor(timespan / day);
const hours = Math.floor((timespan % day) / hour);
const minutes = Math.floor((timespan % hour) / minute);
const seconds = Math.floor((timespan % minute) / second);
//if it is the day of the event
if (timespan <= 0 && timespan > -day) {
document.write(
`
<div>
<h1>HAPPY ${newName.toUpperCase()}!!!</h1>
</div>
`
);
return;
}
//write to the document
document.write(
`
<div>
<ul>
<li>There are</li>
<li>${days} days</li>
<li>${hours} hours</li>
<li>${minutes} minutes</li>
<li>${seconds} seconds</li>
<li>until your ${newName}</li>
</ul>
</div>
`
);
//run countdown function every second
setTimeout(countdown, 1000);
}
</script>
</body>
</html>