문제

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!

도움이 되었습니까?

해결책

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:

  1. You call getVideoDuration()
  2. You get the first <video> tag.
  3. You add an event listener to it for the loadedmetadata event.
  4. Your getVideoDuration() function completes and exits and returns nothing.
  5. 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);
    });
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top