Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting a Javascript counter into 00:26

I have some Javascript code that is basically an "elapsed" timer for a file upload. Here's the code:

// Update elapsed
var time = new Date().getTime() - startTime;
var elapsed = Math.floor(time / 100) / 10;
console.log(elapsed);

Using this, I get logs in the console looking like: 0.7, 0.8, 0.9, 1, 1.1, 1.2 etc. These are seconds and the number after the . is 10ths of a second. I want to format this into a more human readable form, for example, 26 seconds would be 00:26, 1 minute 30 seconds would be 01:30, 20 minutes would be 20:00 etc.

However, I've got no idea how I can properly write a function to convert it into a human readable form.

like image 336
James Dawson Avatar asked May 07 '26 01:05

James Dawson


1 Answers

http://jsfiddle.net/69dgJ/1/

function formatSecs(secs) {
    secs = parseInt(secs);
    ss = secs % 60;
    mm = Math.floor(secs / 60.0);
    if(ss < 10) { ss = "0" + ss; }
    if(mm < 10) { mm = "0" + mm; }
    fmt = mm + ":" + ss;
    return fmt;
}
like image 131
Heitor Chang Avatar answered May 09 '26 13:05

Heitor Chang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!