title: Performance of a simple jQuery slider
body: <p>I am learning jQuery and I have been trying to make a slider from scratch. Even though it works, the performance is not as smooth as I would like. I even tried toying with DOM caching, but performance still isn't perfect.</p>
  
  <p>How can I improve it and, if possible, how can I shorten the code even more?</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>'use strict';
  
  var $slider = $('#slider');
  var $slides = $('#slides');
  var $slide = $('.slide');
  
  var slideWidth = $(window).width();
  $('#slider, #slider img').css({
      'width': slideWidth
  });
  
  var slidesWidth = slideWidth * ($('.slide').length + 1);
  $slides.css({
      'width': slidesWidth
  });
  
  var currentSlide = 1;
  
  $(function () {
      var animationSpeed = 1600; 
      var pause = 5000;
  
      setInterval(function () {
          $slides.animate({
              'margin-left': '-=' + (slideWidth + 5.5)
          }, animationSpeed, function () {
              currentSlide++;
              if (currentSlide === $slide.length) {
                  currentSlide = 1;
                  $slides.css({
                      'margin-left': '0'
                  });
              }
          });
      }, pause);
  });</code></pre>
  <pre class="snippet-code-css lang-css prettyprint-override"><code>*, *::after, *::before {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box; }
    
  body {
   margin: 0;
      padding: 0;
      min-width: 320px;
  }
  
  #slider {
      overflow: hidden;
      margin: 0;
      padding: 0;    
  }
  
  #slides {
      margin: 0;
      padding: 0;
  }
  
  .slide { 
      display: inline-block;
      list-style-type: none;
      margin: 0;
      padding: 0;
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;
  &lt;!-- HTML relevant segment --&gt;
  
  &lt;div id="slider"&gt;
      &lt;ul id="slides"&gt;
          &lt;li class="slide"&gt;&lt;img src="http://bit.ly/1ez08le"/&gt;&lt;/li&gt;
          &lt;li class="slide"&gt;&lt;img src="http://bit.ly/1ez08le"/&gt;&lt;/li&gt;
          &lt;li class="slide"&gt;&lt;img src="http://bit.ly/1ez08le"/&gt;&lt;/li&gt;
          &lt;li class="slide"&gt;&lt;img src="http://bit.ly/1ez08le"/&gt;&lt;/li&gt;
          &lt;li class="slide"&gt;&lt;img src="http://bit.ly/1ez08le"/&gt;&lt;/li&gt;
      &lt;/ul&gt;
  &lt;/div&gt;</code></pre>
  </div>
  </div>
  </p>