简体   繁体   中英

Show current video time on a timer (hours:minutes:seconds)

I have a simple timer which is displaying the current time of a video on my page. Sadly it's limited to only showing minutes and seconds, if the video duration is longer than the timer can handle, it will at some point start displaying an incorrect value. After one hour, it will start displaying something like 61:01 (min:sec) And that's a real issue.

 let video = document.querySelector('video'); let counter = document.querySelector('p'); let hrs, mins, secs; window.setInterval(() => { mins = Math.floor(video.currentTime / 60); secs = Math.floor(video.currentTime % 60); if (secs < 10) { secs = '0' + String(secs); } counter.textContent = mins + ':' + secs; },1000);
 <video controls src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" height='200px' width='330px'></video> <p></p>

Sadly I don't have any hour long videos to show the issue.... So could somebody please explain me how should I build this small function so it's capable of displaying hours? Right now I only found a buggy and very unreliable way but it's too pathetic for being shown here.

Do you like?

<video
  controls
  src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
  height="200px"
  width="330px"
></video>
<p></p>

<script>
  function secondsToHms(d) {
    d = Number(d);
    var h = Math.floor(d / 3600);
    var m = Math.floor((d % 3600) / 60);
    var s = Math.floor((d % 3600) % 60);

    var hDisplay = h + ":";
    var mDisplay = m + ":";
    var sDisplay = s;

    return hDisplay + mDisplay + sDisplay;
  }

  let video = document.querySelector("video");
  let counter = document.querySelector("p");
  let hrs, mins, secs;

  window.setInterval(() => {
    counter.textContent = secondsToHms(video.currentTime);
  }, 0);
</script>

Happy codding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM