I'm working on quite a unique project and have a variable that calls my function, is it possible to have it where after it makes 1 function call, it stops working and becomes useless.
Asked
Active
Viewed 141 times
0
-
2See http://stackoverflow.com/questions/12713564/function-in-javascript-that-can-be-called-only-once – soktinpk Oct 25 '14 at 21:55
-
what "it"? the function? the variable? why do you think you need this? probably there would be a better way to design your code... – The Paramagnetic Croissant Oct 25 '14 at 21:56
1 Answers
1
var limiter = function (limit, cb) {
var counter = limit;
return function () {
if (counter > 0) {
cb(counter);
counter--;
}
};
};
var counting = limiter(3, function (data) {
console.log('This function can be used ' + data + ' more times.');
});
for (var i = 0; i < 5; i++) {
counting();
};
Calling limiter with the first paramater as 1 and the second parameter as the function definition will allow you to run the function only one time. In this example, I have created the function 'counting' that will log how many more calls it has until it is useless (It only run three times, despite the for loop calling it five times). The for loop at the bottom just shows that it works. You can also create multiple functions using limiter, without the counters overlapping, as they will each have their own unique scope.

Jacob Turner
- 1,691
- 1
- 11
- 15