Sending file[type="file"] multiple content as list of base64's There is a code that takes all files from input of multiple files, gets base64 for each of them, packs to array and jsonifies it. How to simplify and improve quality of code?

text = $('#input-' + id).val();
var files = document.querySelector('#files' + id + ' &gt; input[type=file]').files;
if (text != '' || files.length &gt; 0) {
    var files_obj = [];
    var reader = new FileReader();
    reader.onload = function(readerEvt) {
        var binaryString = readerEvt.target.result;
        files_obj.push(btoa(binaryString));
    };
    for (var i = 0; i &lt; files.length; i++) {
        reader.readAsBinaryString(files[i]);
    }
    while (files_obj.length &lt; files.length) {}
    $('input[type="file"]').val("");
    files_json = JSON.stringify(files_obj);
    json = '{"action": "message", "from": ' + userId + ', "text": "' + text + '", "room": ' + id + ', "files": ' + files_json + '}';
    socket.send(json);
    $('#input-' + id).val("");
}
while (files_obj.length &lt; files.length) {}


That's not the correct way to wait for the FileReader. onload will get called whenever a file has been successfully read, so you can check for files.length there, and call the rest of the function as needed. Right now you're spin-looping during at least partly CPU intensive (base64 encoding) operations. Which is a huge waste.