views:

16

answers:

2

I have a slider that rotates between different divs nicely with the following code:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt;
<script type="text/JavaScript">
$(document).ready(function (){


    function showSlide(integer) {
        $('#myslide .cover').css({left:-960*(integer-1)}).hide().fadeIn(); 
        $('#button a').each(function(){
        $(this).removeClass('active');
            if($(this).hasClass('button'+integer)){
                $(this).addClass('active')}
        });

        $('#button a').click(function(){
        var integer = $(this).attr('rel');
        $('#myslide .cover').css({left:-960*(parseInt(integer)-1)}).hide().fadeIn(); 
        $('#button a').each(function(){
        $(this).removeClass('active');
            if($(this).hasClass('button'+integer)){
                $(this).addClass('active')}

                });
            });
        setTimeout(function() {showSlide((integer % 5) + 1);}, 5000);


    }

    setTimeout(function() { showSlide(2); }, 5000);


});
</script>

When a user clicks on any of the tabs, the slider jumps to that tab, but the timer keeps counting and automatically in less than 5 seconds it continues automatically flowing where it was.

How could I make that the timer stops when a user clicks on any of the tabs?

+1  A: 

When you use setTimeout, set it so a variable so you can later use clearTimeout. For example,

var timeout = setTimeout(function() {showSlide((integer % 5) + 1);}, 5000);
clearTimeout(timeout);

Good luck :)

John Strickler
+1  A: 

Store a reference to the timeout and clear it when the user clicks.

var timeout;
function showSlide(integer) {
    $('#myslide .cover').css({left:-960*(integer-1)}).hide().fadeIn(); 
    $('#button a').each(function(){
    $(this).removeClass('active');
        if($(this).hasClass('button'+integer)){
            $(this).addClass('active')}
    });

    $('#button a').click(function(){
        clearTimeout( timeout );
        var integer = $(this).attr('rel');
        $('#myslide .cover').css({left:-960*(parseInt(integer)-1)}).hide().fadeIn(); 
        $('#button a').each(function(){
            $(this).removeClass('active');
            if($(this).hasClass('button'+integer)){
                $(this).addClass('active')
            }

        });
    });
    timeout = setTimeout(function() {showSlide((integer % 5) + 1);}, 5000);
}
timeout = setTimeout(function() { showSlide(2); }, 5000);
BBonifield