Use a global variable to track the number of times the function is called.
var counter = 0;
function func() {
counter++;
if (counter > 2) return;
// do other fn stuff
}
On a slightly related note, there is a better way of binding multiple click handlers when using jQuery:
$('div[id^="element"]').click( func );
Of course, it doesn't really matter since return
will halt execution, but if you didn't want func
to be called at all (i.e. if you wanted to remove the click event altogether), you could then simply do (if you make the change above):
$('div[id^="element"]').unbind('click');
This would be in place of the return
statement in the first section of code.