javascriptfor-loopuploadprogressxmlhttprequest-level2

Javascript For Loop To Slow for Progress Event Listener Fireing


I am trying to change a element background color according the the progress of an upload. The problem I am having is the for loop is way to slow compared to the progress event listener that fires off. Is there anything I can do about this?

var colors = [
    "#fff2f2",
"#ffe6e6",
"#ffd9d9",
"#ffcccc",
"#ffbfbf",
"#ffb3b3",
"#ff9999",
"#ff7373",
"#ff8080",
"#ff5959",
"#ff4d4d",
"#ff4040",
"#ff3333",
"#ff2626",
"#ff1919",
"#ff0d0d",
"#ff0000",
]

var first = 0;
var last = 5;
var xhr = new XMLHttpRequest();

xhr.upload.addEventListener("progress", updateProgress, false);

var foo = document.getElementById("uploadScreen");
var form = document.getElementById("uploadForm");
var percentComplete;

xhr.open("POST", "php/upload.php", true);
xhr.send(new FormData(form));

function updateProgress(event) {
    if (event.lengthComputable) {
        percentComplete = Math.round(event.loaded / event.total * 100);
        for (i=0; i < colors.length; i++) {
            if (percentComplete > first && percentComplete < last ) {
                console.log(foo.style.backgroundColor = colors[i]);
                break;
            }
        }
        first = first +5;
        last = last +5;
    } else {
        alert("no no");
    }
}

Solution

  • Rather than getting a whole number as a percent, leave it as a value between 0 and 1. Then just multiply that by the length of your array to get the correct index.

    var percentComplete = event.loaded / event.total;
    var index = Math.round(percentComplete * (colors.length - 1)); // Subtract 1 to account for zero based indexing
    foo.style.backgroundColor = colors[index];
    

    http://jsfiddle.net/h6bsU/