0

I'm trying to make a carousel that runs automatically, but if a user interacts with the controls I want the carousel to reset its timer. What ive built works to an extent, but if you interact with the control-dot the timer isnt reset so it throws some funny results...

Here's my JS

/* Js for carousel */
$('.steps__step-1').addClass('active');
$(function() {
  var lis = $('.step'),
    currentHighlight = 0;
  N = 5; // Duration in seconds
  setInterval(function() {
    currentHighlight = (currentHighlight + 1) % lis.length;
    lis.removeClass('active').eq(currentHighlight).addClass('active');
  }, N * 1000);
});

$('.control-dot').on('click', function(e) {
  e.preventDefault();
  $('.active').removeClass('active');
  var itemNo = $(this).index() - 1;
  $('.step').eq(itemNo).addClass('active');
});

http://jsfiddle.net/tnzLha3o/1/

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Liam
  • 9,725
  • 39
  • 111
  • 209
  • Possible duplicate of [Stop setInterval call in JavaScript](https://stackoverflow.com/questions/109086/stop-setinterval-call-in-javascript) – Liam Jan 14 '19 at 13:50
  • 3
    did you flag your own question as a duplicate? that's not common.. – Kaddath Jan 14 '19 at 13:54

2 Answers2

0

You should store interval id in a variable (let intervalId = setInterval(...)) and then use it to restart it.

Here is your updated fiddle: http://jsfiddle.net/gudzdanil/uzoydp6a/2/

So that your code will look like:

var duration = 5;
var lis = $('.step'),
    currentHighlight = 0;
var intervalId = null;
$(function() {
  $('.steps__step-1').addClass('active');
  runCarousel();
});

$('.control-dot').on('click', function(e) {
  e.preventDefault();
  $('.active').removeClass('active');
  var itemNo = $(this).index() - 1;
  $('.step').eq(itemNo).addClass('active');
  rerunCarousel();
});

function rerunCarousel() {
  if(intervalId) clearInterval(intervalId);
  intervalId = null;
  runCarousel();
}

function runCarousel() {
  intervalId = setInterval(function() {
    currentHighlight = (currentHighlight + 1) % lis.length;
    lis.removeClass('active').eq(currentHighlight).addClass('active');
  }, N * 1000)
}

Danil Gudz
  • 2,233
  • 16
  • 16
0

Add a variable to stop it.

 var stop = false
    $('.steps__step-1').addClass('active');
    $(function() {
        var lis = $('.step'),
            currentHighlight = 0;
            N = 5; // Duration in seconds
        setInterval(function() {
            if (!stop) {
            currentHighlight = (currentHighlight + 1) % lis.length;
            lis.removeClass('active').eq(currentHighlight).addClass('active');
            }
        }, N * 1000);

    });

    $('.control-dot').on('click', function(e){
        e.preventDefault();
        $('.active').removeClass('active');
        var itemNo = $(this).index() - 1;
        $('.step').eq(itemNo).addClass('active');
        stop = !stop
    });

http://jsfiddle.net/quvgxz63/

Jingshao Chen
  • 3,405
  • 2
  • 26
  • 34