Reputation: 4253
I have a setInterval()
inside a function. I'd like to create a status bar to show the user how much time is left until the setInterval()
completes its time.
Any ideas how to do this? I tried but no success.
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>
Upvotes: 0
Views: 772
Reputation: 6957
A bit more dynamic and error-proof solution:
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>
Upvotes: 1
Reputation: 108
You need to use setInterval to update progressbar and clearInerval when the desidered time has passed
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();
Upvotes: 1
Reputation: 16764
A little adjustements from Vladu Ionut's answer:
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();
Sample here: http://jsfiddle.net/dpvfc582/2/
Upvotes: 1
Reputation: 8193
Here is an example based on your code ( The stop condition should be improved )
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>
Upvotes: 2