How do I find out how many times a function is called with javascript/jquery?

Easy version: make a global variable like in codeling’s answer. The problem – if some other code also defines a global variable with the same name, you’re both in trouble.

Easy extended version – give the variable a crazy name that nobody will ever use: calledTimesED7E69A7B141457CA8908A612E3D7A3A

Clever version: append that variable to an existing global variable. Remember – everything’s an object in Javascript!

$(function(){ setInterval(myFunction, 3000); });

function myFunction()
{
    myFunction.calledTimes++;
    alert( "I have been called " + myFunction.calledTimes + " times" );
}
myFunction.calledTimes = 0;

Traditional version: use scoping to hide that variable.

$(function()
{
    var calledTimes = 0;
    setInterval(function()
    {
        calledTimes++;
        alert( "I have been called " + calledTimes + " times" );
    }, 3000); 
});

This hides “myFunction” though, so let’s try again with a tricky kind of scoping:

var myFunction = null;
(function()
{
    var calledTimes = 0;
    myFunction = function()
    {
        calledTimes++;
        alert( "I have been called " + calledTimes + " times" );
    } 
})();

$(function () { setInterval(myFunction, 3000); });

… and there are a zillion other ways you would hide that variable with scoping. Just pick your favorite.

Leave a Comment