I’m trying in js to get a videos current time. I have come up with a rather ugly and not so precise solution, using a setInterval
on the play
event. But i would very much prefer using a better method. Maybe requestAnimationFrame
could do it? I’m open for a better solution.
Current code:
this.video = document.createElement('video')
this.duration = null
this.currentTime = null
this.video.addEventListener('play', this.play)
play(e) {
setInterval(() => {
this.currentTime = this.video.currentTime
}, 1000)
}
>Solution :
I think what you’re looking for is the timeupdate
event.
Example:
let video = document.getElementById("video");
let currentTime = null;
video.addEventListener('timeupdate', timeUpdate);
function timeUpdate(e) {
currentTime = e.target.currentTime;
console.log("Time: " + currentTime);
}
<video id="video" width="400" controls>
<source src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4">
</video>