简体   繁体   中英

JavaScript GET Request Webpage image in Stream

I have a url that has a new jpeg on it everytime you visit the page. I would like to use my javascript get constantly send get statements to that page and retrieve the image to display it on my webpage in as "stream" of images in a container one after the other. Currently I can only get the first image when I run the function. I am new to JavaScript.

    isLive=true;
    let imageurl = SERVICE_URL;
    var ajaxImage = document.getElementById("liveImg");
      do {

            xhttp.open("GET",imageurl, true);
            xhttp.send();
            ajaxImage.src = imageurl;

          }
          while (isLive);

Do not use infinite loops in javascript to do ajax like this because it would send many request without any limit crashing the browser and yes the server as well if there are many clients

What you need instead is a timer that would tick, say every 5 seconds changing the image

isLive=true;
let imageurl = SERVICE_URL;
var ajaxImage = document.getElementById("liveImg");
var timerKey = 0;

function Imgchanger{
    //incase you want to stop it just assign isLive=false somewhere
    if(!isLive){
        clearInterval(timerKey);
    }

    xhttp.open("GET",imageurl, true);
    xhttp.send();
    ajaxImage.src = imageurl;
}

timerKey  = setInterval(imgchanger, 5000); //5 seconds

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM