title: JS changing source image with animation
body: <p>I have a problem with looped fade-in/fade-out image source changing in JS and CSS and using <em>SetTimeout()</em> callback.
  The problem is, that the sequence is working strange: sometimes the image changes before the transition starts, sometimes it works fine, and sometimes in the other way.</p>
  
  <p>Here is my JS:</p>
  
  <pre><code>const animationTime = 5000;
  const transitionTime = 500;
  
  function nextImage() {
  
    let img = document.getElementById('img1');
    img.classList.remove('hidden');
    setTimeout(function () {
      img.classList.add('hidden');
    },animationTime-transitionTime);
    img.src=randomize();
    setTimeout(nextImage, animationTime);
  }
  </code></pre>
  
  <ul>
  <li><em>randomize()</em> function just gets a random image path from array.</li>
  </ul>
  
  <p>Here is HTML:</p>
  
  <pre><code>&lt;div class="some-class"&gt;
      &lt;img class="some-image" id="img1" src="1.png"&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>And here is CSS:</p>
  
  <pre><code>.some-image {
  
    transition: opacity 0.5s linear;
    -webkit-transition: opacity 0.5s linear;
    -o-transition: opacity 0.5s linear;
    -moz-transition: opacity 0.5s linear;
    -moz-border-radius: 15px;
  }
  
  .hidden {
  opacity: 0;
  }
  </code></pre>
  
  <p><strong>Upd.</strong>
   So I have edited CSS file:</p>
  
  <pre><code>.some-image {
      width: 370px;
      height: 190px;
      animation: fade-out;
      animation-duration: 1s;
  }
  
  .hidden {
      animation: fade-out;
      animation-duration: 1s;
  }
  
  @keyframes fade-in {
      from {opacity: 0;}
      to {opacity: 1;}
  }
  
  @keyframes fade-out {
      from {opacity: 1}
      to {opacity: 0}
  }
  </code></pre>
  
  <p>And JS-file:</p>
  
  <pre><code>function nextImage() {
  
          let img = document.getElementById('img1');
          img.classList.remove('hidden');
          setTimeout(function () {
              img.classList.add('hidden');
          },animationTime-1000);
          img.src=randomize();
  
      }
      setTimeout(nextImage, animationTime);
  }
  </code></pre>
  
  <p>And, somehow, it works perfectly on a local machine, but on a dedicated website animation sometimes fades-in before the image source changed.</p>