Amir
Amir

Reputation: 6186

Javascript onload function is not defined

Here is the code:

function getTime(j){
  var stopClock= new Date();
  delta[parseInt(j)]=stopClock.getMilliseconds()-start.getMilliseconds();
 }

 //REST OF THE CODE!!

for (var i = 0; i < 6; i++){
  start = new Date();
  document.write('<img src="'+URL[i]+'" width="1" height="1" alt="" onload="getTime('+i+');"/>');
 }

the problem is sometimes in some values of j (e.g. 3 or 5) it says getTime is not defined! (most of the time is fine)...

I know the it may be because of the fact that when it reaches to that onload line it may not have loaded getTime function yet, but getTime function is at the top of the code and many of the getTime has response...

Upvotes: 1

Views: 3674

Answers (2)

momo
momo

Reputation: 21343

I am not sure what you are trying to do (especially using document.write), but you could try putting the function into a proper scope such a document scope.


    // pass the start time in milliseconds as well
    document.getTime = function(startInMillis, j) {
        var stopClock= new Date();
        delta[j]=stopClock.getMilliseconds()-start.getMilliseconds();
    };

And try using document.getTime() from the next line of code. You also see that I put the start variable in getTime() as well. Given that loading time of the image is not synchronous (though your loop is), you need make sure you pass this into the function otherwise you could have gotten a wrong result.

Upvotes: 2

Tejs
Tejs

Reputation: 41236

I would think the manner of trying to introduce a callback to your request is not the correct path. It sounds like you need to potentially move to another solution perhaps using some jsonP or another technology to get around the same domain policy and then you could attach to the appropriate events.

onload isnt even a proper event for an image tag. onload should only be valid on a <frameset> or <body> tag.

Upvotes: 0

Related Questions