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.

--

--

Full Stack Developer, Speaker and Auth0 Ambassador. Passionate about code, teach and field hockey. Mostly working with JavaScript, Vue.js and Node.js. 🚀

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ignacio Anaya

Full Stack Developer, Speaker and Auth0 Ambassador. Passionate about code, teach and field hockey. Mostly working with JavaScript, Vue.js and Node.js. 🚀