title: How do I kill a setInterval()/setTimout() if I lose the calling object?
body: <p>I'm working on a rather large app, I need to call a function over an over again while a key is being pressed, at a specific interval.  There's parts of the app that I can't edit, but it's replacing my .onkeyup() listeners and sometimes the interval is just left there forever.  What I <em>really</em> want is for the interval to stop when the object gets destroyed, reassigned, etc...  After setInterval(), bindings, closures, I made this to try something out and now I am even more confused:</p>
  
  <pre><code>function myInterval(){
      this.name = 'Paul'
      that=this;
  this.go = function go(){
          if(that){
              this.interval = setTimeout(function(){
                  console.log(that.name);
                  that.go();
              },100);
          };
          console.log(that.name);
      };
  };
  
  periodic = new myInterval();
  periodic.go();
  setTimeout(function(){
      periodic.name='George';
  }, 200);
  setTimeout(function(){
      periodic.name ='John';
      periodic.go = '';
      periodic.name = 'Ringo'
  }, 300);
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>Paul
  Paul
  Paul
  George
  George
  Ringo 
  &gt; Uncaught TypeError: Property 'go' of object #&lt;myInterval&gt; is not a function
  </code></pre>
  
  <p>So, reassigning the function works, but if I replace    </p>
  
  <pre><code>periodic.go = '';
  </code></pre>
  
  <p>with</p>
  
  <pre><code>periodic = '';
  </code></pre>
  
  <p>I get</p>
  
  <pre><code>Paul
  Paul
  Paul
  George
  George
  John
  John
  ...
  </code></pre>
  
  <p>And so on forverer; The interval never stops...  </p>
  
  <ol>
  <li><p>Can anyone explain?</p></li>
  <li><p>Is there a common, elegant solution to ensuring I don't go dropping running intervals into the aether?</p></li>
  </ol>