Skip to content

Instantly share code, notes, and snippets.

@janmisek
Last active August 29, 2015 14:22
Show Gist options
  • Save janmisek/bebfd584ce3382a67ce2 to your computer and use it in GitHub Desktop.
Save janmisek/bebfd584ce3382a67ce2 to your computer and use it in GitHub Desktop.
run function once
once

There are times when you prefer a given functionality only happen once, similar to the way you'd use an onload event. This code provides you said functionality:

function once(fn, context) { 
	var result;

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

		return result;
	};
}

Usage

var canOnlyFireOnce = once(function() {
	console.log('Fired!');
});



canOnlyFireOnce(); // "Fired!"
canOnlyFireOnce(); // nada

The once function ensures a given function can only be called once, thus prevent duplicate initialization!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment