In Javascript, queuing the execution of function if the function is already executing, but cancel any previously queued
<p>I've faced the following scenario quite often so I'm wondering if there is a built-in jQuery way of solving the issue.</p>

<p>Imagine the following code:</p>

<pre><code>$(document).click(function() {
   paintCanvas();
});
</code></pre>

<p>The problem with this code is that if the user clicks on the screen 50 times in rapid succession you are going to overload the browser with 50 calls to paintCanvas.</p>

<p>If paintCanvas is currently executing and a new request is created, we want to queue the new request so that it waits until paintCanvas is finished executing. However, at the same time, we can drop any previously queued calls to paintCanvas as we only care about the final state of the mouse, not all the intermediate states.</p>

<p>Here is some code that solves the problem:</p>

<pre><code>var _isExecuting, _isQueued;

function paintCanvas() {
    if (_isExecuting) {
        if (!_isQueued) {
            _isQueued = true;
            setTimeout(function() {
                _isQueued = false;
                paintCanvas();
            }, 150);
        }
        return;
    }

    _isExecuting = true;

    // ... code goes here

    _isExecuting = false;
};
</code></pre>

<p><a href="http://www.protofunc.com/scripts/jquery/ajaxManager/" rel="nofollow">This AJAX queue plugin</a> essentially implements this functionality, but does so only in terms of AJAX. Surely this is a very common problem that can be solved in more generic way?</p>
