2
Transition.start = function(){
    for(var j = 0; j < 6; j++)
    {
         console.log("FOR LOOP");
         (function(){
             console.log("INNER Function");
             var image = new Image();
             image.src = path + Config.imgName[j] + ".jpg";
             image.onload = function () {

                 console.log("GONE");
                 clearImages[source].push(image);
                 console.log(image);
             };
         })();
     }
}

In this on console "FOR LOOP" and "INNER Function" is printed 6 times, but "GONE" is printed 12 times. I am not able to figure out the reason for this. I want to run the body of onload also 6 times.

and Transition.start is called from onDocumentKeyDown listener like this

function onDocumentKeyDown( event )
{
    if (keyPressed == 38) //up arrow
        Transition.start();
}
3
  • Show us the code where this function gets called Commented Jun 10, 2015 at 9:54
  • I think console.log(image) is calling the "image.onload" and hence the "GONE" is being print more number of times. Commented Jun 10, 2015 at 9:56
  • Did you try console.trace()? Commented Jun 10, 2015 at 10:09

1 Answer 1

13

I got the the source of the problem. Actually image.onload is called everytime the image is rendered in the browser. Actually I once image is loaded I was storing it in clearImages so that if in future the image is required then it can be taken directly from that array, so if the image is required in future then it is loaded from the clearImages array but again the onload function will be called.

So I solved this thing by doing image.onload = null inside onload function itself

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

Comments

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.