0

I'm trying to gather the times of all videos on a page and add them to an array. Here is the code:

var allvideos = $('video');
var times = [];
for ( i=0; i < allvideos.length; i++ ) {
    allvideos[i].addEventListener('loadedmetadata', function() {
        videoDuration = this.duration;
        times.push(videoDuration);
    });
};

If I console.log(times) within the EventListener, it works as expected but if I log it after the for loop it's empty. I can't figure out why that is. Could someone help, and please explain why? Thanks so much.

I am using jQuery and Video.js.

S

Stu
  • 327
  • 1
  • 3
  • 14
  • 5
    Why would you expect it to be not empty before the event listeners are called ? – Denys Séguret Jun 09 '14 at 16:09
  • Simple. You are placing buckets to collect rain water. Then you expect that all the buckets will be filled immediately after placing them. Please wait until it rains :) – Diode Jun 09 '14 at 16:15
  • So in my case, how do I wait? – Stu Jun 09 '14 at 16:32
  • @Stu in each event listener's callback function you need to check if all the other event listeners have been executed. One way to do this is to check if `times.length === allvideos.length`. See my answer for some code. – David Sherret Jun 09 '14 at 18:43

1 Answers1

3

Think about how your code is executing:

  1. Create times array
  2. Set up event listeners
  3. Output the value in the times array with a console.log
  4. Event listeners are called and push to times array

The reason it is not showing the videoDurations in the times array is because times is empty at that point in time. You have to wait until after all your event listeners have been called before outputting the values in the array.


If you want to output the array after all your event listeners have been called, then you can do something like this:

for (var i = 0; i < allvideos.length; i++) {
    allvideos[i].addEventListener('loadedmetadata', function() {
        times.push(this.duration);

        if (times.length === allvideos.length) {
            console.log(times);
        }
    });
};
David Sherret
  • 101,669
  • 28
  • 188
  • 178