title: Audio object duration keeps changing?
body: <p>I’m trying to get the duration in seconds of every object in a list but I’m having some trouble in my results. I think it’s because I’m not fully understanding asynchronous behavior.</p>
  
  <p>I start my function with an array <code>songs[]</code> of <code>n</code> number of objects. By the end of my function, the goal is to have an array <code>songLengths</code> where the first value is the duration of the first object in <code>songs[]</code>, and so on.</p>
  
  <p>I’m trying to model my function after this example: <a href="https://stackoverflow.com/q/750486/6365949">JavaScript closure inside loops – simple practical example</a>. But I’m getting undefined values for each <code>songLengths[]</code> index.</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>$("#file").change(function(e) {
    var songs = e.currentTarget.files;
    var length = songs.length;
    var songLengths = [];
  
    function createfunc(i) {
      return function() {
        console.log("my val = " + i);
      };
    }
  
    for (var i = 0; i &lt; length; i++) {
      var seconds = 0;
      var filename = songs[i].name;
      var objectURL = URL.createObjectURL(songs[i]);
      var mySound = new Audio([objectURL]);
  
      mySound.addEventListener(
        "canplaythrough",
        function(index) {
          seconds = index.currentTarget.duration;
        },
        false,
      );
      songLengths[i] = createfunc(i);
    }
  });</code></pre>
  </div>
  </div>
  </p>