title: SetInterval, then clearInterval, then setInterval again
body: <p>I have a problem with my slider code.</p>
  
  <p>Here I define a function to animate the slider based on how many elements there are (the more elements, the more times it should slide):</p>
  
  <pre><code>var animateSlider = function() {
  
          var howManyTimes = Math.ceil(newContainerWidth / parentWidth)-1;
  
  
          var repeatSlider = function() {
              howManyTimes = Math.ceil(newContainerWidth / parentWidth)-1;
              for (i=0;i&lt;howManyTimes;i++) {
              // looped code
              $(".portfolio-slider").delay(2000).animate({
                          marginLeft: - (slideDistance * (i+1) )
                      }, 500);
  
              console.log(howManyTimes);
          }
          $(".portfolio-slider").delay(2000).animate({
                          marginLeft: 0
                      }, 500);
      }
  
      // and this is where I set the interval for sliding: 
  
      var intervalId;
      var intervalId = function() {
          setInterval(repeatSlider,howManyTimes * 500);
      }
      intervalId();
  
      // here's where I tried putting:
     // clearInterval(intervalId)
     // just to see if it clears it, but it didn't, the code interval just kept on replaying.
  
      }
  </code></pre>
  
  <p>Here I start the slider if autoplay is set to true:</p>
  
  <pre><code>    // fires the slider if autoplay option is set to true
      if (autoplay) {
      animateSlider();
          }
  </code></pre>
  
  <p>And here's what happens when I click on a button with ".filter" class - it filters the elements (code removed as it works and it's not what I want to focus on) and then initiates the animateSlider function so it can recalculate the number of elements and how many times it's supposed to slide:</p>
  
  <pre><code>        $('.filter').click(function(){
          // it does some stuff and then animates the slider again so it recalculates the widths and number of times it's supposed to slide:
  
          animateSlider();
      });
  </code></pre>
  
  <p>The problem is that I don't think it restarts the function, instead it fires it again and again and it doesn't recalculate how many times the slider should slide (so when I filter elements, it slides empty slides as well as those with elements).</p>
  
  <p>I'm aware of the clearInterval() function, but I've tried putting it under the setInterval without success. </p>
  
  <p>The ideal behavior should be - the slider slides, after a click on ".filter" the interval stops and restarts with new width and number of elements (instead of firing many times without stopping).</p>
  
  <p>It's the second day that I'm trying to deal with this, I would really appreciate some help.</p>