Very simple JavaScript countdown source code

In case you need to make a countdown in your website, here is a handy JavaScript code you can use. Just edit the variable countDownDate and set it the date you want, then run the JS. Watch the console log counting the seconds. It will show an alert message when the countdown reaches zero.

<!DOCTYPE html>
<html>
	<head>
		<title>Simple Countdown</title>
	</head>
	<body>
		

		<script>
			
			//Countdown date:
			var countDownDate = new Date("2023-7-26 5:27").getTime();
			var x = setInterval(function() {

				var now = new Date().getTime();

				var distance = countDownDate - now;

				var days = Math.floor(distance / (1000 * 60 * 60 * 24)).toString();
				var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)).toString();
				var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)).toString();
				var seconds = Math.floor((distance % (1000 * 60)) / 1000).toString();
				
				console.log("days: " + days + " hours: " + hours + " minutes: " + minutes + " seconds: " + seconds);

				// If the count down is finished...
				if (distance < 0) {
					clearInterval(x);
					alert("Countdown Ended!");
				}
			}, 1000);
		</script>
	</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *