Javascript: Dynamic Image creation

I want to upload multiple images and display them on the webpage. Following is the code which I have done ->

let fileInput = document.getElementById("file-input");
let imageContainer = document.getElementById("images-space");
let numOfFiles = document.getElementById("num-of-files");

function preview(){
    imageContainer.innerHTML = "";
    numOfFiles.textContent = `${fileInput.files.length} Files Selected`;
    $("#images_2nd_div_heading").html('<p><b>You have Selected ' + 
   `${fileInput.files.length}` + ' Images.</b> (Click on the images to add Tags)</p>');
    var count = 1;
    var html2='';
    for(i of fileInput.files){
        let reader = new FileReader();
        let figure = document.createElement("figure");
        let figCap = document.createElement("figcaption");
        figCap.innerText = i.name;
        figure.appendChild(figCap);
        reader.onload=()=>{
            let img = document.createElement("img");
            img.setAttribute("src",reader.result);
            img.setAttribute("name","img"+count);
            figure.insertBefore(img,figCap);
        }
        imageContainer.appendChild(figure);
        reader.readAsDataURL(i);
    }

Now the images are loaded perfectly on the webpage. The only problem being that the img.setAttribute used for name is setting "name":img4 if I select 3 Images from the webpage.

I don’t know why it is happening .

Here is the HTML code ->

<div class="container1">
            <input type="file" id="file-input" name="file" accept="image/png, image/jpeg" onchange="preview()" oninput="this.className = ''" multiple>
            <label for="file-input">
              <i class="fa fa-upload choose_photo"></i> &nbsp; Choose Your Photos
            </label>
            <p id="num-of-files">
              No Files Chosen
            </p>
            <div id="images-space"></div>
          </div>
        </div>