I am trying to create a dynamic progress bar forwards and backward with the button controls to stop and resume, how to add the logic to the function? Thanks!
//PROGRESS
function updateBar() {
if (i == 0) {
i = 1;
let filling = document.querySelector(".progress-filling");
let width = 0;
setInterval(update, 5);
function update() {
if (width <= 100) {
width++;
filling.style.width = width + "%";
} else {
width--;
filling.style.width = width + "%";
}
}
}
}
You need to check status of your button (i) inside the update loop and do nothing if it's stopped:
//PROGRESS
let btn = document.querySelector(".btn");
btn.textContent = "STOP";
btn.addEventListener("click", changeInnerHTML);
function changeInnerHTML() {
btn.textContent = btn.textContent === "STOP" ? "RESUME" : "STOP";
if (btn.textContent === "RESUME") {
i = 0;
} else if (btn.textContent === "STOP") {
i = 1;
}
}
let i = 1;
updateBar();
function updateBar() {
let filling = document.querySelector(".progress-filling");
let width = 0;
let step = 1;
setInterval(update, 5);
function update() {
if (!i)
return;
width += step;
filling.style.width = width + "%";
if (width >= 100 || width <= 0)
step = -step; //reverse
}
}
.progress-filling
{
height: 2em;
border: 1px solid black;
background-color: lightgreen;
}
<button class="btn">STOP</button>
<div class="progress-filling"></div>
I used progress element here u can use your wdth etc.... But Checkout the logic I think it's what you are looking for !
<progress id="progress" min="0" max="100" value="0"></progress>
<button id="progress-ctrl">START</button>
<button id="progress-stop">STOP</button>
Js
const progress = document.querySelector('#progress');
const button = document.querySelector('#progress-ctrl');
const sbutton = document.querySelector('#progress-stop');
let interval;
const time = 50; //in ms
button.addEventListener('click', (e)=> {
const text = button.innerText.toLowerCase();
switch (text) {
case 'start':
start();
button.innerText = "PAUSE";
break;
case 'pause':
pause()
button.innerText = "RESUME";
break;
case 'resume':
resume()
button.innerText = "PAUSE";
break;
default:
// nothing to do
}
});
sbutton.addEventListener('click', (e)=> {
sbutton.innerText = "STOPPED";
button.innerText = "START";
stop();
});
function start() {
interval = setInterval(function() {
progress.value += 1
}, time);
sbutton.innerText = "STOP";
}
function pause() {
clearInterval(interval);
}
function resume() {
interval = setInterval(function () {
progress.value += 1
}, time);
}
function stop() {
clearInterval(interval);
progress.value = 0;
}
```