Home › Forums › JavaScript › Slideshow, setTimeout and ClearTimeout
- This topic is empty.
-
AuthorPosts
-
June 21, 2014 at 9:45 pm #173408
cyclingg
ParticipantI 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.
June 23, 2014 at 12:57 am #173448Chromawoods
ParticipantIn
chgSlide
, you clear the timeout, but you never start it again, so that’s why it does not start again. Try invokingrotate
in the end ofchgSlide
.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);
June 23, 2014 at 8:49 pm #173512cyclingg
ParticipantI 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.
-
AuthorPosts
- The forum ‘JavaScript’ is closed to new topics and replies.