AddEventlistener in js cannot modify the value of the global variable

Tobuv :

to get audio's lasted time AddEventlistener in js cannot modify the value of the global variable

      //get last time
        last_time="";
        var audioElement = new Audio(music.listen_file);
        var duration;
        audioElement.addEventListener("loadedmetadata", function (_event) {
            duration = audioElement.duration;
            var min=Math.floor(duration/60 )
            var sec=Math.floor(duration)%60;
            last_time=min+":"+sec;  
        });
        console.log(last_time);
Hank X :

you actually changed the value, move your console.log(last_time); into the callback function you will see the value been changed once the event fired.

  last_time="";
        var audioElement = new Audio(music.listen_file);
        var duration;
        audioElement.addEventListener("loadedmetadata", function (_event) {
            duration = audioElement.duration;
            var min=Math.floor(duration/60 )
            var sec=Math.floor(duration)%60;
            last_time=min+":"+sec;  
            console.log(last_time);
        });

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=30021&siteId=1