javascript countdown script from milliseconds in to hours-minutes-seconds

11,328

Solution 1

Simple maths.

1000 milliseconds = 1 second.

60 seconds = 1 minute.

60 minutes = 1 hour.

So if you have 123456789 milliseconds, you'd do something like:

123456789 / 1000 (to seconds) which is 123456.789

123456.789 / 60 (to minutes) which is 2,057.6

2,057.6 / 60 (to hours) which is 34.29 hours.

Then use the remainder (.2935525) and turn this into minutes - which is 17.61315

Use the remainder again (.61315) and turn it to seconds... which is 36.789

So, in short, 123456789 milliseconds equals 34 hours, 17 minutes and 37 seconds.

I'm sure you can do the JavaScript part yourself.


Okay maybe you need some more help.

DEMO : http://jsbin.com/eqawam/edit#javascript,html,live

var millis = 123456789;

function displaytimer(){
    //Thank you MaxArt.
    var hours = Math.floor(millis / 36e5),
        mins = Math.floor((millis % 36e5) / 6e4),
        secs = Math.floor((millis % 6e4) / 1000);
        $('.count').html(hours+':'+mins+':'+secs);  
}

setInterval(function(){
    millis -= 1000;
    displaytimer();
}, 1000);

Also, for further reading - setInterval may drift. So don't expect this to be 100% accurate. Will setInterval drift?

Solution 2

I'm not sure about what you're asking for, but...

var hours = Math.floor(millis / 36e5),
    mins = Math.floor((millis % 36e5) / 6e4),
    secs = Math.floor((millis % 6e4) / 1000);
Share:
11,328
user759235
Author by

user759235

Updated on June 07, 2022

Comments

  • user759235
    user759235 almost 2 years

    I am looking for a easy way to output milliseconds into hours-minutes-seconds. I have seen some plugins but i dont want to use a plugin in a plugin, and I have seen a lot of countdown snippets but these are using the date, I am using not a date but milliseconds.

    Thanks.

    EDIT: i am looking for a script that counts back from xxxx milliseconds to zero

    //until now i have this

        diff  = 100000000;
    
        function showTimer() {
    
            hours = Math.floor( diff / (1000*60*60) );
            mins  = Math.floor( diff / (1000*60) );
            secs  = Math.floor( diff / 1000 );
    
            $('.count').html(hours+ 'hours' +minutes + 'minutes' +seconds + ' seconds');
        }
    
        setInterval(function(){showTimer()}, 1000 );