JSFiddle - React, Tailwind, and code Playground

by RAX7

HTML

<figure class="images"></figure>

CSS

body {
  background-color: #ff9800;
}
.images {
  margin: 0;
  width: 500px;
  height: 200px;
  position: relative;
}

.image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
}

.hide {
  opacity: 0;
  transition: opacity 1000ms linear;
}

.show {
  opacity: 1;
  transition: opacity 1000ms linear;
}

JavaScript

function loadImages(srcs) {
  return new Promise(done => {
    const result = [];
    const total = srcs.length;
    let loaded = 0;

    function onload(event, i) {
      loaded++;
      result[i] = event.type === 'error' ? new Error(event.target) : event.target;
 
      if (loaded === total) done(result);
    }

    for (let i = 0; i < total; i++) {
      const img = new Image();
      img.addEventListener('load', (event) => onload(event, i));
      img.addEventListener('error', (event) => onload(event, i));
      img.src = srcs[i];
    }
  });
}

async function fadeInOutImages(container, images, showDuration, startFrom = 0) {
  images = (await loadImages(images)).filter(img => !(img instanceof Error));
  const total = images.length;

  const els = images.map((img, i) => {
    const el = document.createElement('div');
    el.classList.add('image', 'hide');
    el.style.backgroundImage = `url('${img.src}')`;
    return el;
  });
  els.forEach((el) => container.appendChild(el));

  let cur = startFrom;
  let next = (cur + 1) % total;

  els[cur].classList.add('show');

  function tick() {
    els[cur].classList.remove('show');
    els[next].classList.add('show');
    cur = next;
    next = (cur + 1) % total;
    setTimeout(tick, showDuration);
  }
  setTimeout(tick, showDuration);
}

const images = [
  'https://placehold.it/500x200/F44336/FFFFFF?text=slide%200',
  'https://placehold.it/500x200/3F51B5/FFFFFF?text=slide%201',
  'https://placehold.it/500x200/009688/FFFFFF?text=slide%202',
  'https://placehold.it/500x200/607D8B/FFFFFF?text=slide%203',
];

fadeInOutImages(document.querySelector('.images'), images, 5000);