I have a page with 10 images that are hosted on amazon aws and for some reason the retrieval is very slow etc.
I am trying now to show a page without any images for thumbnails and then use AJAX call to get them. So since one particular image "fetching" cycle in the PHP script could take a really long time, I've created an Interval inside an example script that will eventually call a controller/method URL that will, in turn, retrieve the correct image for each thumb "slot", based on some other parameters, ID's of entities etc. ( a lot of stuff involved in this ).
I managed to do an AJAX call on every 2 seconds ( based on interval of course ), but I don't want to wait full 2 seconds to fetch another image in the set, if AJAX call completes in, for example, 0.5 seconds ( wasting 1.5 seconds of pure wait time there ).
So I am trying to figure out here how to, when jQuery ajax.done() is called, I could "break out" of this wait time of interval wait time cycle and make another AJAX call straight away. Tried doing it a couple of ways, but to vain.
HTML and JS:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css"/>
</head>
<body>
<ul class="thumbs">
<li><img src="images/no-image.jpg" alt="buffalo soldier"/></li>
<li><img src="images/no-image.jpg" alt="buffalo soldier"/></li>
<li><img src="images/no-image.jpg" alt="buffalo soldier"/></li>
<li><img src="images/no-image.jpg" alt="buffalo soldier"/></li>
</ul>
<script src="https://code.jquery.com/jquery-2.2.1.min.js"></script>
<script>
$(document).ready(function() {
var thumbsList = $('.thumbs'), // ul of images
// append loader image to all images that need loading
// ( if to be appended as loader image to images one by one, when ajax call is made, do this in the interval function instead )
totalImagesToFetch = thumbsList.find('li img').attr('src', 'images/loader.gif').length,
currentPosition = 0;
// kreiraj interval koji fetchuje sliku po sliku
var fetchThumbInterval = setInterval(function() {
console.log('called');
// dont call interval anymore if we fetched all the needed image thumbs
if(currentPosition >= totalImagesToFetch - 1) clearInterval(fetchThumbInterval);
fetchMeNewThumb = $.ajax({
url: "process.php",
method: "POST"
});
fetchMeNewThumb.done(function(data) {
console.log(currentPosition);
thumbsList.find('li img:eq(' + currentPosition + ')').attr( "src", data ); // String: URL for image src attribute
currentPosition++;
resetInterval(fetchThumbInterval, 2000);
});
}, 2000);
function resetInterval(intervalName, miliseconds) {
clearInterval(intervalName);
setInterval(intervalName, miliseconds);
}
});
</script>
Simple CSS:
.thumbs li {
display: block;
}
.thumbs li img{
width: 400px;
height: 400px;
}
And the images used are just some random images found online. P.S. ( it works correctly and calls AJAX every 2 seconds, if you comment out the call to resetInterval()
function :)