I have a task that requires me to send an ajax request to display an image that changes every 10 seconds. However, I'm encountering an issue where my webpage remains blank for the first 10 seconds and only displays the first image after the initial delay.
var images = [
{ uri:'photo-1539154444419-e31272d30a31.jpg', description:'medium-coated black-and-white dog near grass during daytime' },
{ uri:'photo-1553882809-a4f57e59501d.jpg', description:'black and tan Belgian dog' },
{ uri:'photo-1554196721-b507d7e86ee9.jpg', description:'gray dog standing on grass' },
{ uri:'photo-1555661059-7e755c1c3c1d.jpg', description:'black dog behind plants' },
{ uri:'photo-1555991415-1b04a71f18c5.jpg', description:'adult white Samoyed beside man and woman' },
{ uri:'photo-1558121591-b684092bb548.jpg', description:'white and black dog lying on sofa' },
{ uri:'photo-1559440165-065646588e9a.jpg', description:'person holding dog leash short-coat black and white dog' },
{ uri:'photo-1560160643-7c9c6cb07a8b.jpg', description:'short-coated brown and white dog'
},
{ uri:'photo-1562220058-1a0a019ab606.jpg', description:'pet dog laying on sofa' },
{ uri:'photo-1565194481104-39d1ee1b8bcc.jpg', description:'short-coated gray dog' }
];
var k = 0;
router.get('/images.json', function(req, res, next) {
res.send(images[k]);
k++;
if (k == 10){
k=0;
}
});
In HTML:
<!DOCTYPE HTML>
<html>
<head>
<title>gallery.html</title>
</head>
<body>
<img id ="image"<img src="data:," alt>
<p id ="imagePara"></p>
<script>
setInterval(function () {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState ==4 && this.status == 200){
var json = this.responseText;
var jsonObj = JSON.parse(json);
var desc = JSON.stringify(jsonObj.description);
var uriImage = JSON.stringify(jsonObj.uri);
var uriImage2 = uriImage.substring(1, uriImage.length-1);
var thisImage = document.getElementById("image");
thisImage.src = "images/doggos/"+uriImage2;
thisImage.alt = desc;
var para = document.getElementById("imagePara");
para.innerHTML = desc;
}
};
xhttp.open("GET","/images.json",true);
xhttp.send();
}, 10000);
</script>
</body>
</html>
Seeking assistance with this issue. Thank you!