user1532669
user1532669

Reputation: 2378

How to invoke a closure within a function when counting number of times function is invoked

I want to count the number of times a function is called on click. I have this so far but its not quite working. Can anyone help with this?

function test(){
    var count = (function({
        var i = 0;
        return function(){
           return i += 1;
        }
     })();

   if(count() == 2){
     // do this
   }

}

Invoke the function like so:

<select onclick="javascript: test();">

It looks like the count function isn't being invoked properly. How can I invoke the function and perform an operation on it? I want to perform logic at certain numbers of clicks.

Upvotes: 0

Views: 531

Answers (3)

PeterS
PeterS

Reputation: 2964

Does this work for you?

    var i = 0;
    function test(){
        var count = (function() {
            return function(){
               return i += 1;
            }
         })();
       if(count() == 2){
         console.log('reached goal')
         // do this
       }
    
      alert('current count' +i)
    
    }
<select onclick="test()"><option>select</option></select>

And on your item just:

onlick="test()"

You generally had brackets in the wrong place etc and was always setting the value to 0.

Upvotes: -2

Thijs
Thijs

Reputation: 2351

You could use a closure to wrap the call.

function countUsage(methodToWrap, methodContext) {
  const
    wrapContext = methodContext || this;
  let
    count = 0;
  
  // Return a method, this is the wrapped call.
  return function methodWrapper() {
    // Increase the counter by 1.
    count++;
    // Call the original method with the arguments.
    methodToWrap.apply(wrapContext, arguments);
    // Log the number of times the method was called.
    console.log(`The method has been called ${count} times`); 
  }
}

function methodToWrap(text) {
  console.log(`Log line ${text}`);
}

function sumToWrap(a, b) {
  console.log(`Sum of ${a} + ${b} = ${a+b}`);
}

const
  wrappedLog = countUsage(methodToWrap),
  wrappedSum = countUsage(sumToWrap);

// For these three calls you will see the count is increased with each call.
wrappedLog('hello');
wrappedLog('how');
wrappedLog('are you');

// This will result in a log line that there has been 1 call as it is a different method.
wrappedSum(3, 4);

Upvotes: 1

Escoute
Escoute

Reputation: 396

var count = 0;
function test(){
   count++;
   if(count == 2){
     // do this
     console.log('do something');
   }
}
<label onclick="javascript: test();">Test</label>

Take a variable and increment on number of click and do your operation.

Upvotes: 2

Related Questions