-1

I've code a piece of code that goes like this:

$('img').load(function(){
    $(this).doStuff(); // here could be one, two, or more images
    doSomethingElse(); // I want this part to run only ONCE
});
function doSomethingElse(){
    // code here unfortunately runs one, two, or more times (depending on how many imgs there are)
}

I'm not sure how to apply jQuery .one() in this situation. I've tried searching online for a way to run something only once, but all I ever seem to find are recommendations to try using jQuery .one().

There must be some way to run doSomethingElse only once, even if multiple images are loaded. I suppose I could use a setTimeout and wait for all the images to have loaded, but I would be guessing how long this takes so that solution seems a bit weak.

Tushar
  • 85,780
  • 21
  • 159
  • 179
user2777052
  • 157
  • 3
  • 11
  • You can look into [Self Invoking Function](http://stackoverflow.com/questions/18203897/a-self-invoking-anonymous-function-expression). Basic syntax: `(function(){})()`. These function will execute only once when file is loaded. – Rajesh Oct 31 '15 at 17:56
  • try this `$('img').load(function(){ $(this).doStuff(); // here could be one, two, or more images doSomethingElse(); // I want this part to run only ONCE return; // make it run only once });` – Ari Oct 31 '15 at 18:09

1 Answers1

1

You could accomplish this using a simple boolean flag:

var done = false;

$('img').load(function(){
    $(this).doStuff(); // here could be one, two, or more images

    if (!done)
    {
        done = true;
        doSomethingElse(); // I want this part to run only ONCE
    }
});

function doSomethingElse(){
    // code here unfortunately runs one, two, or more times (depending on how many imgs there are)
}

This way, you set your done variable the first time the load function runs, and each time it runs thereafter, it skips the call to doSomethingElse().

Vince
  • 3,207
  • 1
  • 17
  • 28