Search code examples
javascriptasynchronousfetch-api

How to get seamless display in javascript slideshow


I've written a basic slideshow with javascript. It downloads a randomly-chosen JPEG from a CGI script, scales it down if necessary, deletes the previously-displayed slide and displays the new one on the page, repeating this every two seconds.

The problem is that some of the JPEGs are very large (from 3MB to 20MB). The downloading (and, I presume, the scaling) take so long that sometimes, when the previous slide is deleted, several seconds elapse before the next one appears.

I'm sure this is because of the asynchronous nature of the processing, but I don't know how to control it. What I'd like is for each slide to appear for a minimum of two seconds or long enough that the next slide will appear without any delay.

(I'm using a placeholder image generator in this demo, so I don't know how well it will illustrate the delay problem.)

    function showSlides() {
        const my_img = document.createElement('img');
        fetch('https://picsum.photos/2000/600')
            .then(my_response => my_response.blob())
            .then(my_blob => {
                const my_url = URL.createObjectURL(my_blob);
                my_img.setAttribute('src', my_url);
                my_img.setAttribute('class', 'picture-div-img');
            })
            .catch(my_error => console.error('Error: ', my_error));

        /* NOTE: would like to wait until new slide is completely downloaded
           and rendered offscreen before deleting current slide and displaying
           new one */

        /* Delete current slide */
        const my_parent = document.querySelector('#slide-div');
        while (my_parent.firstChild) {
            my_parent.removeChild(my_parent.firstChild);
        }
        /* Insert new slide */
        my_parent.appendChild(my_img);
        setTimeout(showSlides, 2000); /* Change image every 2 seconds */
    }
    html {
        height: 100%;
        width: 100%;
    }

    body {
        /* prevent body from displacing */
        margin: 0;
        /* body should perfectly superimpose the html */
        height: 100%;
        width: 100%;
    }

    .outer-div {
        display: flex;
        flex-flow: column;
        height: 100%;
        /* Now create left/right margins */
        margin: 0 0.5em;
    }

    .inner-fixed-div {
        margin-top: 0.5em;
    }

    .inner-remaining-div {
        margin-bottom: 1em;
        flex-grow: 1;
        /* hints the contents to not overflow */
        overflow: hidden;
    }

    .picture-div {
        /* force the div to fill the available space */
        width: 100%;
        height: 100%;
    }

    .picture-div-img {
        /* force the image to stay true to its proportions */
        width: 100%;
        height: 100%;
        /* and force it to behave like needed */
        object-fit: scale-down;
        object-position: center;
    }
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

</head>

<body onload="showSlides();">
  <div class="outer-div">
    <div class="inner-fixed-div">
      <h1>Lorem Ipsum</h1>
    </div>
    <div class="inner-remaining-div">
      <!-- This div will hold the <img> -->
      <div id="slide-div" class="picture-div">
      </div>
    </div> <!-- end of inner-remaining-div -->
  </div> <!-- end of outer-div -->
</body>
</html>


Solution

  • Perhaps what you really want is to wait 2 seconds after getting the image then repeat. Here we use a promise timer borrowed from this answer https://stackoverflow.com/a/39914235/125981 to do so;

    No need to remove and insert, just update the source.

    const sleep = ms => new Promise(r => setTimeout(r, ms));
    
    async function showSlides(duration) {
      const my_parent = document.querySelector('#slide-div');
     // let mySource = "";
      const my_img = document.createElement('img');
      my_img.setAttribute('class', 'picture-div-img');
      my_parent.appendChild(my_img);
      fetch('https://picsum.photos/2000/600')
        .then(my_response => my_response.blob())
        .then(my_blob => {
         let mySource = URL.createObjectURL(my_blob);
          sleep(duration).then(() => {
            my_parent.querySelector('img').src = mySource;
            showSlides(duration);
          });
        })
        .catch(my_error => console.error('Error: ', my_error));
    }
    showSlides(2000);
    html {
      height: 100%;
      width: 100%;
    }
    
    body {
      /* prevent body from displacing */
      margin: 0;
      /* body should perfectly superimpose the html */
      height: 100%;
      width: 100%;
    }
    
    .outer-div {
      display: flex;
      flex-flow: column;
      height: 100%;
      /* Now create left/right margins */
      margin: 0 0.5em;
    }
    
    .inner-fixed-div {
      margin-top: 0.5em;
    }
    
    .inner-remaining-div {
      margin-bottom: 1em;
      flex-grow: 1;
      /* hints the contents to not overflow */
      overflow: hidden;
    }
    
    .picture-div {
      /* force the div to fill the available space */
      width: 100%;
      height: 100%;
    }
    
    .picture-div-img {
      /* force the image to stay true to its proportions */
      width: 100%;
      height: 100%;
      /* and force it to behave like needed */
      object-fit: scale-down;
      object-position: center;
    }
    <div class="outer-div">
      <div class="inner-fixed-div">
        <h1>Lorem Ipsum</h1>
      </div>
      <div class="inner-remaining-div">
        <div id="slide-div" class="picture-div">
        </div>
      </div>
    </div>