This should work:
$(document).ready(function() { var n = 0; $('div').click(function() { n++; if(n == 3) { $('div').fadeOut('slow'); } }); });
I am wondering why your while not blocking execution while it is sitting and spinning. JavaScript is not multithreaded; there is one thread of execution, and I would suggest that while blocks this thread. But otherwise it will not work, because you never check the value of n before you disappear from the div. That is why extinction occurs almost immediately. Also, there is no need for multiple calls to $(document).ready(...) ; one will do.
I would also recommend using .on :
$(document).ready(function() { var n = 0; $('div').on('click', function() { n++; if(n >= 3) { $('div').fadeOut('slow'); } }); });
This works because n , which was defined in an anonymous function (passed in .ready ), is available for callback (closure) passed in .on or .click . Closures are lexically related to the area in which they are defined, which means that everything that is defined in the closed area is available for closure. That way your n value will be updated and available for closing.
source share