JavaScript GET请求流中的网页图片

问题描述 投票:0回答:1

我有一个网址,有一个新的jpeg上,每次你访问的页面。我想用我的javascript不断地发送get语句到该页面,并检索图像显示在我的网页上,作为 "流 "的图像在一个容器一个接一个。目前,我只能得到第一个图像时,我运行的函数。我是一个新的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);
javascript rest loops stream jpeg
1个回答
0
投票

不要在javascript中使用无限循环来做像这样的ajax,因为它会发送许多请求,没有任何限制,崩溃的浏览器,是的服务器,以及如果有许多客户端。

你需要的是一个 定时器 滴答声,比如说每5秒改变一次图像。

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
© www.soinside.com 2019 - 2024. All rights reserved.