0

I have a fiew movie in my website and I cant play movie.

This is code in java. I send name of video id to javascript:

for(int i=1; i<=Integer.parseInt(film[0][0]); i++)
         {

             nr="id"+Integer.toString(i);
             printWriter.print("<input type='hidden' id=\""+nr+"\" name='numerId' value='"+film[i][0]+"' />");

         }

This is code in javascript:

var test2=[];
var test3=[];
var myVideoTab= new Array();
for(i = 1; i < size; i++){
test2[i]='id'+i;
test3[i]=document.getElementById(test2[i]).value;
myVideoTab[i]= document.getElementById(test3[i]);
setTimeout(function () {myVideoTab[i].Play();}, 1000); //in this line is error

This is the error: Uncaught TypeError: Cannot read property 'Play' of undefined. If i set

   myVideoTab1= document.getElementById(test3[i]);
   setTimeout(function () {myVideoTab1.Play();}, 1000);

it work but only one video play

Shomz
  • 37,421
  • 4
  • 57
  • 85
4pablo
  • 3
  • 1
  • 1
  • 3

1 Answers1

1

The problem is that, by the time the code runs, i is already size+1, which is an index you don't have.

The quickest fix would be to wrap it in an anonymous function call with i as a parameter:

function(val){setTimeout(function () {myVideoTab[val].Play();}, 1000)}(i);

That would ensure that the current value of i is used (changed the parameter name to val, for easier understanding).


This simple example show values of both good (wrapped) and bad (unwrapped) values for each iteration:

var div = document.getElementById('r');
var output = "";
for (var i = 0; i < 10; i++) {
   setTimeout(function() {
     output += '<p class="u">unwrapped i is ' + i + '</p>';
     div.innerHTML = output;
   }, 1000);
   (function(val){
     setTimeout(function() {
       output += '<p>wrapped i is ' + val + '</p>';
       div.innerHTML = output;
     }, 1000)
   }(i));
}
p {
  color: green;
  }
p.u {
  color: red;
  }
<div id="r"></div>
Shomz
  • 37,421
  • 4
  • 57
  • 85