Reputation: 297
function getVideoDuration() {
var myVideo = document.getElementsByTagName('video')[0];
myVideo.addEventListener('loadedmetadata', function {
var duration = (Math.round(myVideo.duration));
return duration;
});
}
I will be simple and direct...
I want to get out the duration value of the function inside add.EventListener. However this is not working as expected, and I think it's not possible...
Am I right? If so, what kinda of alternatives do I have?
Thanks in advance!
Upvotes: 0
Views: 7858
Reputation: 707716
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:
getVideoDuration()
<video>
tag.loadedmetadata
event.getVideoDuration()
function completes and exits and returns nothing.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);
});
}
Upvotes: 1