Tom
Tom

Reputation: 845

How can I loop through this array using javascript?

Given this script:

<html>
<head>

<script>
var sentences= 
[
 ['journey27.mp4', 
  [
    [1, 2],
    [5, 7]
  ]
 ],
 ['journey28.mp4', 
  [
    [10, 12],
    [13, 17],
    [25, 36]
  ]
 ],
 ['journey30.mp4', 
  [
    [13, 15],
    [15, 19],
    [21, 30]
  ]
 ]
];

function playVideo(myUrl, startTime, endTime) { 
  var video = document.getElementById("myVideo");
  video.src = myUrl;
  video.currentTime=startTime;
  video.play();

  var maxTime = endTime;
  video.addEventListener("timeupdate", function(){
    if(video.currentTime >= maxTime){
     playVideo(myUrl, startTime, endTime);
    }
  }, false);
} 

function myLoop(){
  I want to loop each pairs 5 times before jump to the next pair
}
</script>
</head>
<body>
<video id="myVideo" width="1000" height="800" controls autoplay loop>

  Your browser does not support the video tag.
</video>

<br>
<a  onclick="myLoop()" > Play </a>

</body>
</html>

Now I want to fill in myLoop function.

I want to loop each pairs 5 times before jump to the next pair in the array.

For example, -the first pair: 'journey27.mp4', loop "[1, 2]" 5 times

then the next pair: 'journey27.mp4', loop "[5, 7]" 5 times

then the next pair: 'journey28.mp4', loop "[10, 12]" 5 times

then the next pair: 'journey28.mp4', loop "[13, 17]" 5 times

and so on

Note: The playVideo function above works

How can I loop through this array using javascript?

Upvotes: 0

Views: 71

Answers (1)

Barmar
Barmar

Reputation: 780724

Use global variables to hold the current indexes and repetition count for the video. Increment the repetition count, and when reaches 5 increment the indexes.

There's no loop, the iteration happens when the user clicks the link.

var sentences= 
[
 ['journey27.mp4', 
  [
    [1, 2],
    [5, 7]
  ]
 ],
 ['journey28.mp4', 
  [
    [10, 12],
    [13, 17],
    [25, 36]
  ]
 ],
 ['journey30.mp4', 
  [
    [13, 15],
    [15, 19],
    [21, 30]
  ]
 ]
];

function playVideo(myUrl, startTime, endTime) { 
  console.log(`Playing ${myUrl} from ${startTime} to ${endTime}`);
} 

let video_index = 0;
let time_index = 0;
let repeat = 0;

function myLoop(){
  playVideo(sentences[video_index][0], sentences[video_index][1][time_index][0], sentences[video_index][1][time_index][1]);
  repeat++;
  if (repeat >= 5) {
    repeat = 0;
    time_index++;
    if (time_index >= sentences[video_index][1].length) {
      time_index = 0;
      video_index++;
    }
  }
}
<a href="#" onclick="myLoop()" > Play </a>

Upvotes: 2

Related Questions