2

Hello please anyone help me.

I have some code like below

    let duration;

    let video = document.createElement('video');
    video.setAttribute("id", 'test')
    video.setAttribute("src", "https://vdoelearning.s3-ap-southeast-1.amazonaws.com/Charlie%2BPuth%2B-%2BOne%2BCall%2BAway.mp4");
    video.preload = 'metadata'
    video.ondurationchange = function() {
        duration = video.duration
    }

    console.log(duration)

Why variable duration is always undefined? I've been searching on google but did not find any solution. Has anyone ever had a problem similar to mine?

KalyanLahkar
  • 835
  • 8
  • 21

2 Answers2

0

the problem is that "ondurationchange()" is called asynchronously (in some undefined time after the listener is added) whyle you make the console.log after the declaration so duration is yet undefined... if you put the console.log inside the listener you'll see proper log when duration effectively changes

video.ondurationchange = function() {
    duration = video.duration
    console.log(duration)
}
Roberto Bisello
  • 1,235
  • 10
  • 18
  • thx for answering my question, But could it be the duration variable I can call in another function ? because I need the duration value for other functions. – edvin megantara Nov 09 '17 at 08:10
  • yes, you can, but you need to be awere that you're working in an asynchronous environment, so you need to use an event-driven approach or a series of callback to correctly handle the changes – Roberto Bisello Nov 09 '17 at 08:55
0

You are calling console.log(duration) directly after adding your function to the ondurationchange event. So it's normal that it returns undefined, it's only filled when the event gets triggered at least once.

Move your console.log to the callback function right under duration and you will see when it's actually called. Also your video is never playing with this code so I doubt the event will be raised.

Huso
  • 1,501
  • 9
  • 14
  • Thank you for answering my question. Could it be the duration variable I can call in another function ? because I need the duration value for other functions. – edvin megantara Nov 09 '17 at 08:08