Skip to main content

Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

  • This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #173408
    cyclingg
    Participant

    I am creating a slideshow of 5 images and have it automatically advance every 3 seconds and also manually advance by clicking the forward arrow (and backwards).

    I used the setTimeout function to advance every 3 seconds and then used the clearTimeout function within my chgSlide(direction) function to stop the auto advance.

    When I stop clicking the next or previous arrows, the auto advance does not kick in.

    How do you start it up again (no jQuery)?

    javaScript code:

    var pause = 3000; //interval, in milliseconds, between transitions
    var i = 0; //image counter
    
    //last index in 'imgs' array
    var imgCt = imgs.length - 1;
    
    var pic = document.getElementById("pic"); //the <img> element in the HTML file
    
    var timer;
    //rotate between the images in the "imgs" array
    function rotate()
    {
        pic.src = imgs[i];
        if (i === (imgs.length -1))
        {
            i = 0;
        }
        else
        {
            i++;
        }
        
        timer = setTimeout("rotate()", pause);
    }
    
    window.onload = rotate;
    
    //transitions either forward or backward
    function chgSlide(direction)
    {
        clearTimeout(timer)
        
        i += direction;
        if (i > imgCt)
        {
            i = 0;
        }
        
        if (i < 0)
        {
            i = imgCt;
        }
        
        pic.src = imgs[i];
    }

    I am not sure if I used the clearTimeout properly; but, it works on my computer. Before I added this, the slideshow did not work that smoothly (skipped an image or two when clicking).

    Thanks.

    #173448
    Chromawoods
    Participant

    In chgSlide, you clear the timeout, but you never start it again, so that’s why it does not start again. Try invoking rotate in the end of chgSlide.

    Regarding setTimeout: Instead of passing a string that invokes the rotate function, you can simply pass a reference to it, like this:

    timer = setTimeout(rotate, pause);
    
    #173512
    cyclingg
    Participant

    I ended up doing a work around.

    I created another function;
    function stopSlide()
    {
    clearTimeout(timer);
    }

    Then I add an “auto” button and a “stop” button. The “auto” button uses the rotate() function and the “stop” button uses stopSlide() function.
    This seems to work now.

    I will try your solution and see if that works also.

    Thanks.

Viewing 3 posts - 1 through 3 (of 3 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.