I have a simple slideshow which automatticlly changes the image using setInterval every 5 seconds.
The user can also move from one image to another using previous and next links.
If the user clicks the prev/next links the timer isn’t interupted, so for example, if the timer is on 3 seconds when the user clicks the link the next image is only displayed for 2 seconds before being changed again.
I know I could do this by using clearInterval and then using setInterval again but is there a cleaner way?
Here’s my code if you need it:
//Move to next image every 10 seconds unless paused.
var timeInterval = 5000;
var featureSlide = window.setInterval(function() { nextFeature("next")}, timeInterval);
$("a#feature-prev").click( function () {
nextFeature("prev");
return false;
});
$("a#feature-next").click( function () {
nextFeature("next");
return false;
});
function nextFeature(action) {
var idNow = $("ul#features li:visible").attr("id");
var pos = idNow.replace("feature-", "");
//If image is currently animated do nothing
//If this isn't in place then multiple images are displayed
if ($("li#" + idNow).is(":animated")) {
return;
} else {
if (pos == 4 && action == "next") {
pos = 1;
} else if (pos != 4 && action == "next") {
pos++;
} else if (pos !=1 && action == "prev") {
pos--;
} else if (pos == 1 && action == "prev") {
pos = 4
}
pos = "feature-" + pos;
// Slide to next image
$("li#" + idNow).hide("slide", { direction: "right" }, 1000, function () {
$("li#" + pos).show("slide", { direction: "left"}, 1000);
});
}
}
Thanks!
You can’t restart the timer without cancelling and restarting it.
Alternatively you could stop using
setIntervalentirely, and just usesetTimeout. Schedule the next one whenever you show an image (just after theshowinnextFeatureif I’m reading your code right). Then the interval reset happens as a by-product of your logic flow, rather than being a special thing.