3

Continuously request an image until it is found

 2 years ago
source link: https://www.codesd.com/item/continuously-request-an-image-until-it-is-found.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Continuously request an image until it is found

advertisements

I am working on an interface that allows for an image to be uploaded asynchronously, and the process is working as expected. The process submits the image to a backend process that manages resizing the image to different sized and stores them on the cloud. i generate the url, and eventually the image is uploaded (usually in less than 10 seconds) to the appropriate resize.

After the image is uploaded, there's no thumbnail displayed for that image in the interface, obviously, because it hasn't been resized yet.

What I'd like to do, is, after creation of the image, and submission to the backend service for resize, a process on the client attached to each upload attempt (which I am thinking of using a setinterval for) to keep looking for that image until it resolves, and once it does resolve, update the thumbnail placeholder with that image.

Once the image does resolve by request, how do I feed that to update the interface?


Pure JavaScript using the setTimeout, onerror and onload events:

var img,
    attempt = 2;

checkForImage("https://ssl.gstatic.com/apps/cpanel/resources/img/apps_logo_new.png3",
             document.getElementById("message"));

function checkForImage(location, loadto) {
    img = document.createElement("img")

    img.onerror = function () {
        setTimeout(function() {
            checkForImage(location, loadto);
            loadto.innerText = "Finding Picture... Attempt: " + attempt++;
        }, 5000);
    }

    img.src = location;

    img.onload = function () {
        loadto.innerHTML = "<img src='" + location + "' />";
    }
}

Removing the 3 at the end of the image link will show a successful example.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK