0

Beginner here, so my problem is only the last function in the let videos = [] array works. The other functions work as well but only when they're the last index in the array. So I've tried assigning the functions to variables and put them in the let videos = [] array and all the videos played at the same time. I have these set up to hide the other videos when 1 video is playing.

Also, I'm trying to make sure each video only plays 1 time.

function playNextVideo() { 
    let videos = [showVideo1(), showVideo2(), showVideo3()]; 
    let randomVideo = Math.floor(Math.random() * videos.length); 
    videos.splice(randomVideo,1); 
}

document.getElementById('video1').addEventListener('ended',playNextVideo(),false);
2
  • 1
    randomVideo is index, so you should use return videos[randomVideo] and does showVideo1() return function? Commented Apr 23, 2021 at 4:35
  • Yes, it used to make the video visible only when it was the last item in the array, but that part is solved now. :) Commented Apr 23, 2021 at 4:58

1 Answer 1

2

Rather than invoke all three functions and worry about hiding the videos you don't want, just store references to the functions and execute only one at a time:

function playNextVideo() { 
    let videos = [ showVideo1, showVideo2, showVideo3 ]; 
    let randomVideo = Math.floor( Math.random() * videos.length ); 

    videos.splice(randomVideo, 1)[0](); // Splice out the element at position randomVideo. You'll get back an array of 1 element, so extract the 0th element (a function) and call it
}

Sign up to request clarification or add additional context in comments.

4 Comments

better answer than what I suggested earlier.
This works! 2 small problems though. The video doesn't auto-play to the next video and each video can only play 1 time. I got an answer to that here: stackoverflow.com/questions/67101727/… but I'm not sure how to apply that to my new situation.
I've updated my answer to remove the video from the array before playing it, so videos only play once. As for auto-playing the next video, you'll have to add an event handler to the videos so that when they finish, they automatically call the playNextVideo() function. Since you provided no details of the implementation of the actual videos, you're on your own for that part.
I found a simple solution, all I had to do was remove the parenthesis on the function in the event listener. Works 100% now!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.