Skip to content Skip to sidebar Skip to footer

Call A Function Only If It Hasn't Been Called / Run A Function Only Once

I have a function animate_images running on some of my website's pages that performs a certain animation. The problem I'm experiencing is that when a user navigates to the same pa

Solution 1:

Take a look at the once function from underscore.js - linked here.

Essentially, you wrap the function in another one that has a flag variable inside it. Call the function if the flag is unset and set the flag when you call it.

_.once = function(func) {
  var ran = false, memo;
  returnfunction() {
    if (ran) return memo;
    ran = true;
    memo = func.apply(this, arguments);
    func = null;
    return memo;
};

};

If you don't want to add underscore to your website (I think that's the first thing you should do when starting any website, but I digress), do this:

runOnlyOnce = function(func) {...} // As defined above

animate_images = runOnlyOnce(animate_images);

or

animate_images = runOnlyOnce(function(){
    alert('Animate all the things!');
});

The function itself has no dependencies on the rest of underscore.

Solution 2:

Use a static property of your function object, as in a boolean animate_images.isRunning. At the start of animate_images, encapsulate the animation initialization with something like

animate_images() {
    // on first load, animate_images.isRunning is undefined,//     so (!animate_images.isRunning) returns true.if(!animate_images.isRunning) { 
        /* launch animation */;
        // define animate_images.isRunning and assign true
        animate_images.isRunning = true;
    } else { 
        /* animation already initialized */ 
    }
}

Solution 3:

You could override your function with an empty function once it has been executed:

functiona(){
    console.log("hello");
    a = function(){};
}

a();  //"hello"a();  //>>nothing happens<<

Actually this will just override the reference a to your function. So this only works if you don't reference to the same function multiple times. If you do something like this:

functiona(){
    console.log("hello");
    a = function(){};
}

var obj { b:a };

a();  //"hello"a();  //>>nothing happens<<
obj.b(); //"hello"

this method will fail.

Post a Comment for "Call A Function Only If It Hasn't Been Called / Run A Function Only Once"