JSFiddle - React, Tailwind, and code Playground

by TrevorBurnham

HTML

<a href="#" id="clickme">Click me</a>

<p id="clickcount">
  How many times can you click in 1 second? The count will be shown here.
</p>

<p id="lateclicks">
  And clicks that occurred in the next second will be shown here.
</p>

<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 func1, func2, x, h, start, interrupt, clickCount, lateClicks;

var clickme = document.getElementById('clickme');
var pClickCount = document.getElementById('clickcount');
var pLateClicks = document.getElementById('lateclicks');

var start = function() {
  clickCount = 1;
  lateClicks = 0;
  clickme.onclick = incrementClickCount;
  loopFor1s();
  clickme.onclick = incrementLateClicks;
  loopFor1s();
  setTimeout(function(){
    pClickCount.innerHTML = 'Clicks: ' + clickCount;
    pLateClicks.innerHTML = 'Clicks: ' + lateClicks;
    clickme.onclick = start;    
  }, 0);
  return false;
};

var incrementClickCount = function() {
  clickCount++;
  return false;  
}

var incrementLateClicks = function() {
  lateClicks++;
  return false;    
}

var loopFor1s = function() {
  var startTime = (new Date).getTime();
  while ((new Date).getTime() - startTime < 1000) { continue; }
};

clickme.onclick = start;