Simple version: make a global variable, as in nyarlathotep answer . The problem is if any other code also defines a global variable with the same name, you are both in trouble.
A simple extended version is to give the variable a crazy name that no one will ever use: calledTimesED7E69A7B141457CA8908A612E3D7A3A
Smart version: add this variable to an existing global variable. Remember - the whole 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 scope to hide this variable.
$(function() { calledTimes = 0; setInterval(function() { calledTimes++; alert( "I have been called " + calledTimes + " times" ); }, 3000); });
This hides "myFunction", so let's try again with a tricky look:
var myFunction = null; (function() { calledTimes = 0; myFunction = function() { calledTimes++; alert( "I have been called " + calledTimes + " times" ); } })(); $(function () { setInterval(myFunction, 3000); });
... and there are two million more ways to hide this variable with scope. Just choose your favorite.
Vilx-
source share