gpt4 book ai didi

javascript - setInterval() 仅触发一次

转载 作者:行者123 更新时间:2023-12-03 02:07:14 28 4
gpt4 key购买 nike

我尝试在图像上传开始时每 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,但这并没有发生。

编辑:

这是工作 fiddle :

https://jsfiddle.net/7tmcu5g6/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">

关于javascript - setInterval() 仅触发一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49751157/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com