Reputation: 1580
I want to increase the value of a progessbar. When reaching its maximum it should stop. This code should simulate a server call, the user has to wait and the inputs should be disabled.
function serverCall() {
var container = $("#disabledBackgroundContainer"),
progressBar = $("#progressBar"),
duration = 5000,
currentProgess = 0,
steps = 1;
progressBar.prop("max", duration);
container.css("display", "block");
currentProgess = setInterval(function () {
currentProgess += steps;
progressBar.val(currentProgess);
if (currentProgess >= duration) {
clearInterval(currentProgess);
container.css("display", "none");
}
}, steps);
}
#disabledBackgroundContainer {
top: 0;
left: 0;
width: 100%;
height: 100%;
display: none;
position: absolute;
background-color: #333333;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn btnDark" onclick="serverCall()">Server Call</button>
<div id="disabledBackgroundContainer">
<progress id="progressBar"></progress>
</div>
As you can see, the progessbar never stops and it seems I got a loop in my code. But I don't get the right way to handle this.
Upvotes: 1
Views: 3143
Reputation: 350147
You are using currentProgess
for two different things: a timer ID and an incremental number you want to check.
You need to use two different variables for those:
var timer = setInterval(function () {
currentProgess += steps;
progressBar.val(currentProgess);
if (currentProgess >= duration) {
clearInterval(timer);
container.css("display", "none");
}
}, steps);
Secondly, remove the hash from the HTML id
property. Should be id="progressBar"
. The hash only has meaning as a CSS selector (in your code and style section):
function serverCall() {
var container = $("#disabledBackgroundContainer"),
progressBar = $("#progressBar"),
duration = 5000,
currentProgess = 0,
steps = 1;
progressBar.attr("max", duration);
progressBar.attr("value", 2000);
container.css("display", "block");
var timer = setInterval(function () {
currentProgess += steps;
progressBar.attr('value', currentProgess);
if (currentProgess >= duration) {
clearInterval(timer);
container.css("display", "none");
}
}, steps);
}
#disabledBackgroundContainer {
top: 0;
left: 0;
width: 100%;
height: 100%;
display: none;
position: absolute;
background-color: #333333;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn btnDark" onclick="serverCall()">Server Call</button>
<div id="disabledBackgroundContainer">
<progress id="progressBar"></progress>
</div>
Upvotes: 2