title: JavaScript's setTimeout function making unexpected, multiple calls
body: <p>I've tried to simplify a problem I'm having with the code below. Some of the code relies on jQuery, fyi.</p>
  
  <p>Basically, I expect that when 'New Thing' is clicked, a single alert message will appear. However, if one starts the timer, clicking 'New Thing' results in an unexpected behavior where the number of alert messages that appear is equal to the time elapsed. </p>
  
  <p>This problem is destroying me.</p>
  
  <p>To be thorough, I've included a complete example. I realize it's a bit lengthy.</p>
  
  <pre>
  $(document).ready(function() {
      mainLoop();
  });
  
  var counter = 0;
  var timerIsOn = 0;
  var t;
  
  function mainLoop() {
      handleInput();
      timer();
  }
  
  function timerHandle() {
      if (!timerIsOn){
          timerIsOn = 1;
          timer();
      }
  }
  
  function timer(){
      if (timerIsOn) {
      t = setTimeout(mainLoop, 1000);
      counter++;
      $("span").text(counter); // To display the elapsed time 
      }
  }
  
  // Just simple buttons
  function handleInput(){    
      $("#timer").click(timerHandle); 
      $("#new").click(createThing);
  }
  
  function Thing() {
      this.talk();
  }
  
  Thing.prototype.talk = function() {
      alert("Hello!");
  }
  
  function createThing() {
      new Thing;
  }
  </pre>
  
  <p>I really appreciate the help!</p>