我在函数中有一个setInterval()
。我想创建一个状态栏,向用户显示在setInterval()
完成其时间之前还剩下多少时间。
任何想法如何做到这一点?我尝试过但没有成功。
function slideSwitch() {
var myInterval = setTimeout(slideSwitch, 3000);
var calc = myInterval / 30;
$("#bottom_status").width(calc);
}
slideSwitch();
#bottom_status {
width: 1px;
height: 1px;
background-color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="bottom_status"></div>
答案 0 :(得分:2)
这是一个基于您的代码的示例(停止条件应得到改善)
progress = 0;
function slideSwitch() {
var myInterval = setTimeout(slideSwitch,100);
progress++;
var calc = progress * 10;
if (progress > 100 ) clearInterval(myInterval);
$("#bottom_status").width(calc);
}
slideSwitch();
#bottom_status{
width:10px;
height:10px;
background-color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id=bottom_status></div>
答案 1 :(得分:1)
Vladu Ionut的答案有一些调整:
var progress = 0;
function slideSwitch() {
var myInterval = setTimeout(slideSwitch,100);
progress++;
var calc = progress * 10;
if (progress > 100 ) {
clearInterval(myInterval);
progress = 0;
return;
}
$("#bottom_status").width(calc);
}
slideSwitch();
答案 2 :(得分:1)
您需要使用setInterval来更新进度条,并在经过指定时间后清除clearInerval
function slideSwitch() {
var maxtime = 3000;
var incremental = 500;
var actualtime = 0;
var interval = setInterval(function() {
actualtime += incremental;
var percentage = 100 / maxtime * actualtime;
$("#bottom_status").width(percentage+"%");
if (actualtime == maxtime) {
clearInterval(interval);
}
}, incremental)
}
slideSwitch();
答案 3 :(得分:1)
更加动态和防错的解决方案:
const wrapper = document.getElementById('wrapper');
const status = document.getElementById('status');
let interval;
function slideSwitch(time) {
const fps = 16;
const slice = wrapper.offsetWidth / (time / fps);
let temp = status.offsetWidth;
interval = setInterval(() => {
temp = temp + slice;
status.style.width = temp + 'px';
}, fps);
setTimeout(() => {
// TODO: switch your slide here
clearInterval(interval);
status.style.width = '0px';
}, time);
}
slideSwitch(3000);
#wrapper {
background: #eee;
}
#status {
width: 0px;
height: 1px;
background-color: #000;
}
<div id="wrapper">
<div id="status" />
</div>