JavaScript: clear setInterval on blur, and resume on focus
<p>I have a very basic slideshow cycling some div containers. This is my code:</p>

<pre><code>function cycle(){
    var $first = $('.panes .pane1');
    var $active = $('.panes .active');
    var $next = $active.next();
    if($next.length != 0){
        $active.removeClass('active').addClass('inactive');
        $('.panes').animate({left: "-=430px"}, 400);
        setTimeout(function(){
            $next.removeClass('inactive').addClass('active');
        }, 400);
    } else {
        $active.removeClass('active').addClass('inactive');
        $('.panes').animate({left: "0px"}, 400);
        setTimeout(function(){
            $first.removeClass('inactive').addClass('active');
        }, 400);
    }

}

$(window).blur(function(){window.clearInterval(cycling)});
$(window).focus(function(){cycling = setInterval('cycle()', 5001);});
</code></pre>

<p>Then in my document.ready function, I'm calling the above with <code>cycling = setInterval('cycle()', 5001);</code></p>

<p>When the page become inactive, the setInterval should clear, then resume when the page regains focus.  This works correctly in Chrome, but not IE.  I'm not really concerned about IE because it doesn't need to be cleared there.</p>

<p>In Firefox, with the above code, the div container just switches back and forth with each interval, or sometimes it slides to the left twice as far as it is supposed to. </p>

<p>When I remove the <code>$(window).focus(function(){cycling = setInterval('cycle()', 5001);});</code> line, then it behaves correctly with the exception of that it does not resume when the page regains focus.</p>

<p>What is causing this and how do I resolve the issue?</p>
