Once Pattern in JavaScript

Ignacio Anaya
Aug 13, 2015 · 1 min read

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.

Ignacio Anaya

Written by

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