0

In this page, user view 1 image at a time. Right: next image. Left: previous image. I'm trying to always buffer next 20 images. One at a time. But I keep failing.

The following code starts to buffer next 20 images at any given time.

I want it to buffer next 1 image at any given time. I don't want it to buffer multiple images simultaneously due to bad Internet connection.

So I tried to get the information "if the latest image to be buffered" finished loading. The following code should have worked. But it doesn't. It "starts to buffer next 20 images, at the same time". (Assume 300msec is 0 for the sake of getting my point across)

(I can provide the whole HTML file if you need but it is very simple and short thus it is not so needed in my opinion) For now I'm only putting the part where I manage buffering. There might be a few unrelated errors because I'm constantly modifying it but the logic relevant to this question should be fine.

setInterval(function(){ 
    var allLoaded = true;
    for(var i=index; i<indexToLoad; i++){
        $("#image"+i).onload = function() {
            console.log("i am a noob");
        }

        $("#image"+i).onerror = function() {
            console.log("be nice");
            allLoaded == false;
        }
    }

    if(allLoaded == true){
        if(indexToLoad-index < 20)
            indexToLoad++;
    }

    var imageId = "image"+indexToLoad;

    if($("#" + imageId).length == 0) {
        $('<img />').attr({src: links[indexToLoad], id: imageId}).appendTo('body').css('display','none');
        //console.log("request" );
    }

}, 300);

Internet connection here is very weak. So I'm trying to only buffer 1 image at a time. But when the image finished loading, then I want it to buffer the next image in the array. Until the next 20 images are completely buffered.

I'm a noob but I spend hours on this problem tried many approaches and failed. How can I achieve my goal?

Any help is appreciated. Thank you!

user3722246
  • 151
  • 4

1 Answers1

1

The simple answer to your problem is to use the image onload event to trigger download of the next image. Start buffering the images with a window.onload event.

var imgIndex = 0;
var imgIndexToLoad = 20;
var links = new Array();    //your src array

function BufferImage(){
    if(imgIndex > imgIndexToLoad){
        return;
    }
    imgIndex++;
    var newImg = new Image();
    newImg.onload = function(){
        document.body.appendChild(this);
        BufferImage();
    };
    newImg.id = imgIndex;
    newImg.src = links[imgIndex-1]; 
}
window.onload = function(){BufferImage();};
OffTheBricks
  • 425
  • 2
  • 9
  • I received about 100 answers so far with my question and yours was the first one useful. Thank you. I solved my problem with an idea you gave me. – user3722246 Feb 26 '16 at 19:06