Countdown that renews at midnight using pure javascript

Asked

Viewed 287 times

1

How to show the hours and minutes remaining to 00:00 hours (midnight) ?

Example:

I have a sales website on which I want to put a countdown that says the time remaining for midnight, which at midnight, will appear 23h 59m 59s.

It’s going to be a kind of propaganda, like, "Run! There’s only XX h XX m XX s left"

If the person has for example at 20:31, will show 3h 29m 00s.

And so whispered....

I saw this example, but I didn’t have the ability to make it work: http://codepen.io/SitePoint/pen/MwNPVq

Only I want something simple, just a text "Xxh Xxm Xxs". No CSS.

1 answer

3


You can do it like this:

function calculateHMSleft()
{
	var now = new Date();
	var hoursleft = 23-now.getHours();
	var minutesleft = 59-now.getMinutes();
	var secondsleft = 59-now.getSeconds();
	if(minutesleft<10) minutesleft = "0"+minutesleft;
	if(secondsleft<10) secondsleft = "0"+secondsleft;
	document.getElementById('count').innerHTML = hoursleft+":"+minutesleft+":"+secondsleft;
}
calculateHMSleft();
setInterval(calculateHMSleft, 1000);
<div id="count"></div>

Answer adapted from here

  • That’s it, I just edited here this part hoursleft+"h "+minutesleft+"m "+secondsleft+"s"; to look like you wanted! Perfect answer! You’re great! ;)

  • Thank you very much!!! D

  • 1

    I was making a version by hand that needed more adjustments. I deleted it. Your reply was faster and it looked very similar to this one: http://shanelabs.com/blog/2011/12/08/end-of-the-day-countdown-in-javascript/ If this is the case, it is good to put references... +1

  • 1

    It was yes with some additions to javascript @Sergio. It’s true, put the reference

Browser other questions tagged

You are not signed in. Login or sign up in order to post.