Created
February 2, 2014 04:37
-
-
Save ZellSnippets/8763134 to your computer and use it in GitHub Desktop.
JS: Make Single Call Function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Two methods to make a single function call | |
*/ | |
// Using a flag | |
var myFun = (function() { | |
var called = false; | |
return function() { | |
if (!called) { | |
console.log("I've been called"); | |
called = true; | |
} | |
} | |
})(); | |
// Replace function with empty function | |
function callonce() { | |
console.log("I've been called"); | |
arguments.callee = function() {}; | |
} | |
/** | |
* Abstracting above two methods: | |
*/ | |
// Call function only once | |
function makeSingleCall(fun) { | |
var called = false; | |
return function() { | |
if (!called) { | |
fun.apply(this, arguments); | |
called = true; | |
} | |
} | |
} | |
// Call function only once | |
// NOTE: arguments.callee is deprecated in ECMAScript 3 | |
function makeSingleCall(fun) { | |
return function() { | |
fun.apply(this, arguments); | |
arguments.callee = function() {}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment