title: jQuery/JavaScript: My recursive setTimeout function speeds up when tab becomes inactive
body: <p>I've got an odd little dilemma in this jQuery slideshow plugin that I am building.</p>
  
  <p>It's nothing fancy and the code I have written to date is working great however I have noticed that when I leave the site running and switch to a new tab and continue browsing the web in this other tab <em>(Chrome for Mac in my case)</em> that when I return to my site, the <code>setTimeout</code> call seems to have speed up and instead of waiting for the timer to finish the fire the event, it fires continuously.</p>
  
  <p>Here is my <em>(simplified)</em> code:</p>
  
  <pre><code>var timer;
  var counter;
  var slides; // collection of all targeted slides.
  
  // animate to the next slide
  function nextSlide() {
  
      // stop timer
      methods.stopTimer();
  
      // increase counter
      counter++;
      if ( counter &gt; slides.length-1 ) { counter = 0; } // if counter is greater than the amount of slides, back to the start.
  
      // inner = container to be animated
      // in the complete callback restart the timer.
      inner.animate({
          'left': '-'+slides.eq( counter ).position().left
      }, {
          duration : settings.animationSpeed,
          easing  : 'easeInOutExpo',
          complete : startTimer()
      });
  
  
  }
  // timer functions.
  function startTimer() {
      if ( timer === '' ) {
          timer = setTimeout( function() {
              nextSlide();
          } , 3000 );
      }
  }
  function stopTimer() {
      clearTimeout( timer );
      timer = '';
  }
  </code></pre>
  
  <p>So what should happen is that at the end of the animation, the timer gets reattached with another <code>setTimeout</code> call so that it becomes a continuous slideshow (and this works just fine until you leave the tab.</p>
  
  <p>Once you leave the tab and return to the tab with slideshow it seems that the <code>3000 ms</code> timer has been reduced to invoke instantly and now the moment the animation finishes the next one starts with no delay at all.</p>
  
  <p>Any ideas on why this is happening on how it can be solved would be much appreciated.</p>
  
  <p>Thanks for reading,</p>
  
  <p>Jannis</p>