Rotation of Videos using Javascript

Step 5: Rotating the Videos

Now lets make the rotate one after another every 20 seconds. After the third video, it will rotate back to the first video. So every 20 seconds a new video will play.

In the script section of the head, create an array called videos to hold the URL of our three videos. We also need a videoIndex to keep track of which video we are playing.

We write an initRotation() function that uses Javascript's built-in setInterval function to set up an interval. The setInterval call shown above tells Javascript to call the rotateVideo() function every 20,000 milliseconds, equivalent to 20 seconds.

What the rotateVideo() function does is to increment the videoIndex to play the next video. The next video gets played when we write out the HTML video code snippet via the writeVideoCode function which we pass the appropriate URL retrieved from our array.

Right after we increment videoIndex, there is the possibility that it will go beyond the length of our videos array. So we have an if-statement to check. If it does, we reset the videoIndex back to 0, our first video.

The thing that kicks this whole process to start is the body onload event. Add the call to initRotation() as shown...

At this point the code should work. When you load the page, the first video should play followed by rotation of the other two videos. And after third video, the first one should play again.

The only problem is when the user clicks on the left video links. The expected behavior is that the rotation would stop so that the user can view the whole video that he/she selected. Unfortunately, the rotation continues. To stop the interval set up by setInterval we have to call the clearInterval. clearInterval takes and id as parameter. This id was returned by setInterval. And if you look back in the above code, we had conveniently saved this id in the global variable intervalId. So to stop the rotation, we call setInterval(intervalId). And we do this in all three of the links...

Everything should work now. We just have to put some finishing cosmetic touches. I want the links to be aligned to the top of the video and to provide user some instructional note by adding the following...

View Live Code Here

Hope you enjoyed the lessons.