Razvan Zamfir
Razvan Zamfir

Reputation: 4616

Reset JavaScript interval instead of clearing it

I am working on a custom image carousel, using jQuery and CSS. My aim is to make it really lightweight but with enough features.

The script has an auto feature that I want to be stopped if the user clicks a bullet. I am using clearInterval for this purpose.

I would like to reset that interval, instead of clearing it. In other words, when the user clicks a bullet, I want that interval between two slides to be a "full" one (of 4 seconds).

Here is the code:

var $elm = $('.slider'),
  $slidesContainer = $elm.find('.slider-container'),
  slides = $slidesContainer.children('a'),
  slidesCount = slides.length,
  slideHeight = $(slides[0]).find('img').outerHeight(false),
  animationspeed = 300,
  animationInterval = 4000;

// Set (initial) z-index for each slide
var setZindex = function() {
  for (var i = 0; i < slidesCount; i++) {
    $(slides[i]).css('z-index', slidesCount - i);
  }
};
setZindex();

var displayImageBeforeClick = null;

var setActiveSlide = function() {
  $(slides).removeClass('active');
  $(slides[activeIdx]).addClass('active');
};

var advanceFunc = function() {
  if ($('.slider-nav li.activeSlide').index() + 1 != $('.slider-nav li').length) {
    $('.slider-nav li.activeSlide').next().find('a').trigger('click');
  } else {
    $('.slider-nav li:first').find('a').trigger('click');
  }
}

var autoAdvance = setInterval(advanceFunc, animationInterval);

//Set slide height
$(slides).css('height', slideHeight);

// Append bullets
for (var i = 0; i < slidesCount; i++) {
  var bullets = '<li><a href="#">' + i + '</a></li>';
  if (i == 0) {
    // active bullet
    var bullets = '<li class="activeSlide"><a href="#">' + i + '</a></li>';
    // active slide
    $(slides[0]).addClass('active');
  }
  $('.slider-nav').append(bullets);
};

var slideUpDown = function() {
  // set top property for all the slides
  $(slides).not(displayImageBeforeClick).css('top', slideHeight);
  // then animate to the next slide
  $(slides[activeIdx]).animate({
    'top': 0
  }, animationspeed);

  $(displayImageBeforeClick).animate({
    'top': "-100%"
  }, animationspeed);
};

$('.slider-nav a').on('click', function(event) {
  event.preventDefault();
  displayImageBeforeClick = $(".slider-container .active");
  activeIdx = $(this).text();
  if ($(slides[activeIdx]).hasClass("active")) {
    return false;
  }
  $('.slider-nav a').closest('li').removeClass('activeSlide');
  $(this).closest('li').addClass('activeSlide');
  
  // Stop autoadvance if user clicks bullet
  if (event.originalEvent !== undefined) {
    clearInterval(autoAdvance);
  }

  setActiveSlide();
  slideUpDown();
});
body * {
  box-sizing: border-box;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
}

.slider {
  width: 100%;
  height: 300px;
  position: relative;
  overflow: hidden;
}

.slider .slider-nav {
  text-align: center;
  position: absolute;
  padding: 0;
  margin: 0;
  left: 10px;
  right: 10px;
  bottom: 2px;
  z-index: 30;
}

.slider .slider-nav li {
  display: inline-block;
  width: 20px;
  height: 3px;
  margin: 0 1px;
  text-indent: -9999px;
  overflow: hidden;
  background-color: rgba(255, 255, 255, .5);
}

.slider .slider-nav a {
  display: block;
  height: 3px;
  line-height: 3px;
}

.slider .slider-nav li.activeSlide {
  background: #fff;
}

.slider .slider-nav li.activeSlide a {
  display: none;
}

.slider .slider-container {
  width: 100%;
  text-align: center;
}

.slider .slider-container a {
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
}

.slider .slider-container img {
  transform: translateX(-50%);
  margin-left: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>


<div class="container">
  <div class="slider slider-homepage">
    <ul class="slider-nav"></ul>
    <div class="slider-container">
      <a href="#">
        <img src="https://picsum.photos/1200/300/?gravity=east" alt="">
      </a>
      <a href="#">
        <img src="https://picsum.photos/1200/300/?gravity=south" alt="">
      </a>
      <a href="#">
        <img src="https://picsum.photos/1200/300/?gravity=west" alt="">
      </a>
    </div>
  </div>
</div>

I have not figured out how to do that.

Upvotes: 0

Views: 111

Answers (1)

cipak
cipak

Reputation: 1456

Like @epascarello said in a comment above, just clear & start again:

if (event.originalEvent !== undefined) {
    clearInterval(autoAdvance);
    autoAdvance = setInterval(advanceFunc, animationInterval);
}

later edit: If the callback or the interval are not available anymore when restarting, it could help to "save" them in a closure:

function startInterval(func, delay) {
    var id = setInterval(func, delay);
    return {
        stop: function() { clearInterval(id); },
        restart: function() { clearInterval(id); id = setInterval(func, delay); }
    };
}

var autoAdvance = startInterval(advanceFunc, animationInterval);

//later
autoAdvance.restart();

Upvotes: 1

Related Questions