Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function count calls

I'm a beginner with JavaScript so please be patient =)

I am trying to write a function that counts the number of times it is called. What I have so far is a function with a counter that is incremented explicitly:

var increment = function () {
    var i = 0;
    this.inc = function () {i += 1;};
    this.get = function () {return i;};
};

var ob = new increment();
ob.inc();
ob.inc();
alert(ob.get());

But I'm wondering how to call only ob();, so the function could increment calls made to itself automatically. Is this possible and if so, how?

like image 698
Kamil Avatar asked Aug 30 '11 12:08

Kamil


People also ask

How do you find out how many times a function is called?

To count how many times a function has been called, declare a count variable outside of the function, setting it to 0 . Inside of the body of the function reassign the variable incrementing it by 1 . The count variable will store the number of function invocations.

How do you count the number of times a function runs in Python?

To use it, simply decorate a function. You can then check how many times that function has been run by examining the "count" attribute. Doing it this way is nice because: 1.)

How do you count the number of times a function is called in C#?

You could use the Performance Profiler in Visual Studio (Analyze > Performance Profiler...). In Available Tools, check Performance Wizard. Start (choose Instrumentation method).

What is used to track how many times a function has been called in angular?

count() method logs the number of times that this particular call to count() has been called.


3 Answers

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

var ob = increment();
like image 110
Marcelo Cantos Avatar answered Oct 11 '22 18:10

Marcelo Cantos


ob = function f(){  
  ++f.count || (f.count = 1);   // initialize or increment a counter in the function object
  return f.count; 
}
like image 35
aljgom Avatar answered Oct 11 '22 19:10

aljgom


Wrap a counter to any function:

/**
 * Wrap a counter to a function
 * Count how many times a function is called
 * @param {Function} fn Function to count
 * @param {Number} count Counter, default to 1
 */
function addCounterToFn(fn, count = 1) {
  return function () {
    fn.apply(null, arguments);
    return count++;
  }
}

See https://jsfiddle.net/n50eszwm/

like image 1
pldg Avatar answered Oct 11 '22 18:10

pldg