Once Pattern in JavaScript

Some times you could have a given functionality which should only be executed one time. Something similar at the way we use an onload event.

Here is a JavaScript function which let you follow this “Once Pattern” and prevent your code to perform an operation if the function has been executed before:

function once(fn, context) { 
var result;

return function() {
if (fn) {
result = fn.apply(context || this, arguments);
fn = null;
}

return result;
};
}

var onceAlert = once(function(){
alert('Show me only once time!');
});

onceAlert(); //This operation will be executed.
onceAlert(); //This operation will not.

Check out this Live Demo.