Jeremy Karlsson
Jeremy Karlsson

Reputation: 1089

JavaScript display duration

I'm trying to make a little counter that display how much a movie has played, like on YouTube.

I want the time to output a like this:

<div id="timeInfo">00:23</div>

How do I achieve this? I tried the following without success:

function infTime (){
    timeInfo.innerHTML = formatTime(video.currentTime);

    if (video.duration) {
        timeInfo.innerHTML = formatTime(video.duration);
    }
}

function formatTime (seconds) {
    seconds = Math.round(seconds);

    minutes = Math.floor(seconds / 60);
    minutes = (minutes >= 10) ? minutes : "0" + minutes;

    seconds = Math.floor(seconds % 60);
    seconds = (seconds >= 10) ? seconds : "0" + seconds;

    return minutes + ":" + seconds;
}

Upvotes: 2

Views: 3630

Answers (2)

Šime Vidas
Šime Vidas

Reputation: 186063

This line is problematical:

seconds = Math.round(seconds);

You want to use Math.floor here to get the correct result.

Live demo: http://jsfiddle.net/simevidas/h6yst/

Upvotes: 1

Pointy
Pointy

Reputation: 413976

You're overwriting the content by assigning to "innerHTML" twice. The second expression could be written with "+=", or else (better) you could build the string separately:

infTime: function() {
  var info = formatTime(video.currentTime) + (video.duration ? ' ' + formatTime(video.duration) : '');
  timeInfo.innerHTML = info;
}

Now, of course that presumes that "timeInfo" is really a reference to the appropriate DOM element, obtained perhaps like this:

var timeInfo = document.getElementById('timeInfo');

Also, do remember to make "minutes" be a local variable by preceding its first use in the "formatTime" function with the var keyword:

    var minutes = Math.floor(seconds / 60);

Upvotes: 0

Related Questions