-1

I have a simple script to play an audio like:

        var audio = new Audio(music)
        var music_duration
        audio.addEventListener('loadedmetadata', function() {
            var duration = audio.duration
            console.log(duration)
            music_duration = duration
        })

        console.log("checking duration")
        console.log(music_duration)

Here music_duration returns undefined..

while duration inside addEventListener gives duration of the music.

I am new to javascript ... What is wrong in here ??

varad
  • 7,309
  • 20
  • 60
  • 112

1 Answers1

0
console.log("checking duration")
console.log(music_duration) 

will be executed before the loadedmetadata event is emitted.

You can check editing the script in this way:

    var audio = new Audio(music)
    var music_duration
    audio.addEventListener('loadedmetadata', function() {
        console.log('here')
        var duration = audio.duration
        console.log(duration)
        music_duration = duration
    })
    console.log('there')
    console.log("checking duration")
    console.log(music_duration)

You'll see there is printed before here.

rpadovani
  • 7,101
  • 2
  • 31
  • 50
  • what is the solution ?? – varad Jun 29 '16 at 09:30
  • @aryan you can move the code you need to execute after the callback in the callback itself - or in another function – rpadovani Jun 29 '16 at 09:31
  • You're merely describing the symptom without addressing the cause. **Asynchronous control** flow and the **run-to-completion guarantee** are the cause of this behavior. –  Jun 29 '16 at 09:45