Search code examples
jqueryhtmljquery-selectorstimercycle

JavaScript timers - clearing, setting new, cycling through divs


I have some JavaScript that cycles through n div tags, displaying only one at a time, and changes every 10s. This is working. But I also have next and previous buttons. They seem to be skipping one div when I click next or previous.

Can someone help?

Any suggestions on a better way to do this is also welcome. I'm new to jQuery so I know some improvements I'd like to do anyway. Thanks!!!

jQuery(document).ready(function () {
    var counter = 1;
    var delay = 3000; //10 seconds = 10000
    var lastItem = jQuery('table[id^=featuredNo]').length - 1;
    var previous = 0;
    var timerID;

    //argument is increment
    //false is decrement
    function updateCounter(increment) {
        if (increment) {
            counter = (counter >= lastItem) ? 0 : counter + 1;
            previous = (previous >= lastItem) ? 0 : previous + 1;
        } else {
            counter = (counter <= 0) ? lastItem : counter - 1;
            previous = (previous <= 0) ? lastItem : previous - 1;
        }
    }

    function displayNext() {
        //alert("testt" + counter);

        //hide everything but current
        jQuery("table[id^=featuredNo]").hide();
        jQuery("#featuredNo" + counter).show();

        //incrememnt the counter, so next time we show the next one
        updateCounter(true);
    };

    //set click handlers for previous
    jQuery('a[id^=featuredPrevious]').click(function () {
        clearInterval(timerID);

        updateCounter(false);

        displayNext();
        timerID = setInterval(displayNext, delay);
    });

    //set click handlers for next
    jQuery('a[id^=featuredNext]').click(function () {
        clearInterval(timerID);

        updateCounter(true);

        displayNext();
        timerID = setInterval(displayNext, delay);
    });


    //start interval
    timerID = setInterval(displayNext, delay);
});

Solution

  • The simplest solution removes updateCounter(true) from your next button handler, and adds another updateCounter(false) to your prev button handler:

    //set click handlers for previous
    jQuery('a[id^=featuredPrevious]').click(function () {
        clearInterval(timerID);
    
        updateCounter(false);
        updateCounter(false);
    
        displayNext();
        timerID = setInterval(displayNext, delay);
    });
    
    //set click handlers for next
    jQuery('a[id^=featuredNext]').click(function () {
        clearInterval(timerID);
    
        displayNext();
        timerID = setInterval(displayNext, delay);
    });