You can't do it the way you're trying to do it. The loadedmetadata
event happens some time in the future. It doesn't happen when getVideoDuration()
is called. Instead, you need to put any code that needs the duration IN the eventlistener where the duration is retrieved or call a function from there and pass it the duration value.
Here's a break-down of the sequencing in your code:
- You call
getVideoDuration()
- You get the first
<video>
tag. - You add an event listener to it for the
loadedmetadata
event. - Your
getVideoDuration()
function completes and exits and returns nothing. - Then, some time later, the
loadedmetadata
event occurs on that video tag and your event handler is called. You fetch the duration and return it back into the event system (e.g. it goes nowhere and is not used by any code).
Here's one way you can do it:
function getVideoDuration() {
var myVideo = document.getElementsByTagName('video')[0];
myVideo.addEventListener('loadedmetadata', function {
var duration = (Math.round(myVideo.duration));
// call a function that needs the duration
myFunction(duration);
});
}