Mdermez
Mdermez

Reputation: 549

Reset timer when using prev next on a slideshow

I have a slideshow with two slides. Each slide holds for 5-6 secs before changing but when I use the prev next buttons it doesn't work well. Somehow it keeps the original timer (from the autoslide) so when I select "next" ,for example 1 sec before the transition then the next slide will stay for just one sec. So when I select next it doesn't reset the timer and instead keeps the original timer.

So in conclusion I want to reset timer within prev next functions (Or if you have any other ideas will be appreciated).

This is the JS:

"use strict";

var currentSlide = 1;
var transition = 1000;
var slideLength = 2;
var slideInter = 6000;

$(".slider ul li:nth-child(" + currentSlide + ")").fadeIn(transition);

$(".next").click(function () {
    nextSlide();
});

$(".prev").click(function () {
    prevSlide();
});

function nextSlide() {
    $(".slider ul li:nth-child(" + currentSlide + ")").fadeOut(transition);
    currentSlide++;
    if (currentSlide > slideLength) 
        currentSlide = 1;
    $(".slider ul li:nth-child(" + currentSlide + ")").fadeIn(transition);
}

function prevSlide() {
    $(".slider ul li:nth-child(" + currentSlide + ")").fadeOut(transition);
    currentSlide--;
    if (currentSlide < 1)
        currentSlide = 2;

    $(".slider ul li:nth-child(" + currentSlide + ")").fadeIn(transition);
}

   //UPDATED CODE   


var timer = setInterval(nextSlide, slideInter);

function resett() {
  clearInterval(timer);}

function timing () {
  timer = setInterval(nextSlide, slideInter);}

$(".slider").hover(resett,timing);

Let me know if you need any additional information or if you didn't understand something from what I said.

Upvotes: 4

Views: 342

Answers (2)

Gabriel Tomitsuka
Gabriel Tomitsuka

Reputation: 1141

Have you tried self-calling recursive functions? It might be a decent work-around.

Something like this:

var isBeingHovered = false;
$('.slider').hover(function(){
  isBeingHovered = true;
}, function(){
  isBeingHovered = false;
  setTimeout(timerFunction, slideInter); //Optional. Resume when stops hovering.
});

(function timerFunction(){
  nextSlide();
  if(isBeingHovered === true)
    setTimeout(timerFunction, slideInter);
})()

Upvotes: 1

Topher
Topher

Reputation: 498

It looks like your timer and the clearInterval are declared and managed under "hover," and aren't called when you trigger nextSlide or prevSlide. Try declaring this as a separate, global function and then call it from within your nextSlide or prevSlide functions so it will reset the timer accordingly when these are run.

Upvotes: 2

Related Questions