javascripthtml5-canvas

Loading indicator during heavy JavaScript


I'm doing some client side image scaling for a phone web app and then send it away. Even for newer iPhones, it sometimes takes a while before the image is downscaled with those big 8MP photos.

Is there a way to show the loading indicator using JavaScript, and only THEN start scaling the image? I DON'T use jQuery so I need a native solution.

Below an example of something I need.. Currently it doesn't show the loading indicator until it actually gets to sending the image through the request... (which is only half a second of in total 3 seconds loading time)

showLoadingIndicator();
loadImage(file,function(canvas){
    heavyRotateStuff(canvas);
    var dataURL = canvas.toDataURL("image/jpeg");

    //Rotated the image here .... << INDICATOR DOESNT SHOW YET

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(ev){
        hideLoadingIndicator();// Were done, hide it, works!
    };
    //Some stuff for sending the image
    xhr.open('POST', 'uploadResized.php', true);
    xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    var data = 'image=' + dataURL;
    xhr.send(data);
    //Indicator finally shows, though were almost done, just waiting for upload to be done..
}

Solution

  • After calling the function to show the indicator, delay the call to processing the image with a setTimeout:

    showLoadingIndicator();
    
    setTimeout(function() {
        loadImage(...);
    }, 20);
    

    As JS is single-threaded it will block the thread when doing the heavy computation which means the browser won't be able to do much else, explaining why the indicator does not show. By delaying the call by a few milliseconds it will give the browser some space to breath and setup the indicator and then do the computation.