setInterval()只触发一次

时间:2018-04-10 10:21:27

标签: javascript

我正在尝试在图像上传开始时每500毫秒更新一个变量,并在上传完成时将其值设置为100。这是代码:

var progress = 0
var $new = document.querySelector('#new');
var $imgupload = document.querySelector('#img-upload');
var $progress = document.querySelector('#progress');
var $percent = document.querySelector('#percent');
var interval = null;

function incrementProgress() {
    interval = window.setInterval(function() {
        $percent.innerHTML = progress+'%'
        $progress.setAttribute('value', progress)
        progress += 2;
        console.log('fired') // fires only once
    }, 500)
}

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            var $img = document.querySelector('#new');
            $img.setAttribute('src', e.target.result);
            $img.style.display = 'block';
        }

        reader.readAsDataURL(input.files[0]);
    }
}

//triggers the setInterval() and initiates image uploading

$imgupload.addEventListener('change', function() {
    incrementProgress();
    readURL(this);
});


//clears the setInterval() on image upload and sets the progress value as 100.

$new.addEventListener('load', function() {
    window.clearInterval(interval);
    $percent.innerHTML = 100+'%'
    $progress.setAttribute('value', 100)
})

问题:

图片上传开始后,$progress的值设置为0,并在图片上传后直接跳至100。期望的是$progess变量每500毫秒增加2,这是没有发生的。

修改

这是工作小提琴:

https://jsfiddle.net/7tmcu5g6/1/

1 个答案:

答案 0 :(得分:1)

也许真正的进展会更好?只需将setInterval替换为reader.onprogress



var $new = document.querySelector('#new');
var $imgupload = document.querySelector('#img-upload');
var $progress = document.querySelector('#progress');
var $percent = document.querySelector('#percent');

function readURL(input) {

    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onprogress = function (e) {
            var progress = Math.round((e.loaded / e.total) * 100);
            $percent.innerHTML = progress + "%";
            $progress.setAttribute('value', progress);
        }

        reader.onload = function (e) {
            var $img = document.querySelector('#new');
            $img.setAttribute('src', e.target.result);
            $img.style.display = 'block';
        }

        reader.readAsDataURL(input.files[0]);
    }
}

$imgupload.addEventListener('change', function () {     
    readURL(this);
});

$new.addEventListener('load', function () {
    $percent.innerHTML = 100 + '%'
    $progress.setAttribute('value', 100)
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<progress max="100" value="0" id="progress"></progress>
<span id="percent">0%</span>
<label for="img-upload">Upload</label>
<input type="file" accept=".jpg, .jpeg, .png" id="img-upload">
<img src='#' id='new' width="200" height="200" style="display: none">
&#13;
&#13;
&#13;