0

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.

1 Answers1

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.

Fiddle: http://jsfiddle.net/Kajdav/acLxxywt/

Jacob Turner
  • 1,691
  • 1
  • 11
  • 15