CoffeeScript

HTML

<script src="https://github.com/jashkenas/coffee-script/raw/master/extras/coffee-script.js"></script>
<a href="#" id="clickme">Click me</a>

<p>
    Click the link once to start a 1-second loop. During that 1 second, click again. Each time you click, you'll trigger an <code>onclick</code> callback that will set <code>x</code> to <code>"interrupted"</code>. At some point, the <code>func2</code> timeout will set <code>x</code> to <code>good</code>. However, if you click the link several times, some of those callbacks will run after <code>func2</code>. An alert will pop up 500ms after the loop to tell you the value of <code>x</code>.
</p>

<p>
    The question is: Is there any way to ensure that the value of <code>x</code> will be <code>good</code>? That is, how can you make <code>func2</code> run after all the input events that the user caused during <code>func1</code> have resolved?
</p>

<p>
    Head to <a href="http://stackoverflow.com/questions/6391536/dom-input-events-vs-settimeout-setinterval-order">http://stackoverflow.com/questions/6391536/dom-input-events-vs-settimeout-setinterval-order</a> if you think you have an answer.
</p>

JavaScript

var clickCount, clickme, func1, func2, interrupt, resetTimeout, start, timeoutHandle;
clickme = document.getElementById('clickme');
timeoutHandle = clickCount = null;
start = function() {
  clickme.onclick = interrupt;
  clickCount = 1;
  func1();
  return false;
};
interrupt = function() {
  clickCount++;
  resetTimeout();
  return false;
};
resetTimeout = function() {
  if (!timeoutHandle) {
    return;
  }
  clearTimeout(timeoutHandle);
  timeoutHandle = setTimeout(func2, 0);
};
clickme.onclick = start;
func1 = function() {
  var startTime;
  startTime = (new Date).getTime();
  while ((new Date).getTime() - startTime < 1000) {
    continue;
  }
  timeoutHandle = setTimeout(func2, 0);
};
func2 = function() {
  alert("The link was clicked " + clickCount + " times");
  clickme.onclick = start;
};