Skip to content

Instantly share code, notes, and snippets.

@bluepnume
Created May 18, 2017 06:15
Show Gist options
  • Save bluepnume/32223ad749852c1f99e9998f25b52d6f to your computer and use it in GitHub Desktop.
Save bluepnume/32223ad749852c1f99e9998f25b52d6f to your computer and use it in GitHub Desktop.
// Create a 'once' function that generates a new function which can only be called once
function sayHello() {
console.log('hello');
}
var sayHelloOnce = once(sayHello);
sayHelloOnce(); // logs 'hello'
sayHelloOnce(); // does nothing
sayHelloOnce(); // does nothing
@wildlingjill
Copy link

wildlingjill commented May 19, 2017

// Create a 'once' function that generates a new function which can only be called once

function sayHello(name1, name2) {
	console.log('hello ' + name1);
    console.log('hello ' + name2);
}

function once (callback) {
  var run = false;
	return function() {
      if (!run) {
        run = true;
        console.log(arguments);
		callback.apply(this, arguments);
      }
	}
}

// or 

function once (callback) {
  var run = false;
	return function(...args) {
      if (!run) {
        run = true;
	callback(...args);
      }
  }
}


var sayHelloOnce = once(sayHello);

sayHelloOnce("Jill", "Daniel"); // logs 'hello'
sayHelloOnce(); // does nothing
sayHelloOnce(); // does nothing

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