Reputation: 27
I've added a timer using a HTML5 progress bar. When clicking on a button, the bar is set on with the following function. It works well, but what I would like to add is trigger an action when the progress is over, and also be able to stop the progress when clicking on another button.
<progress value="0" max="40" id="pbar" ></progress>
<div id="start-stop">
<button id="start" onclick="start_countdown()">Start</button>
<button id="stop">Stop</button>
</div>
...
function start_countdown(){
var reverse_counter = 40;
var downloadTimer = setInterval(function(){
document.getElementById('pbar').value = 40 - --reverse_counter;
if(reverse_counter <= 0)
clearInterval(downloadTimer);
},1000);
}
Upvotes: 0
Views: 247
Reputation: 3589
I hope this works for you. Play, Pause, Stop
<progress value="0" max="40" id="pbar" ></progress>
<div id="start-stop">
<button id="start" onclick="start_countdown()">Start</button>
<button id="stop" onclick="pause_countdown()">Pause</button>
<button id="stop" onclick="stop_countdown()">Stop</button>
</div>
<script type="text/javascript">
var downloadTimer;
var reverse_counter = 40;
function start_countdown(){
downloadTimer = setInterval(function(){
document.getElementById('pbar').value = 40 - --reverse_counter;
if(reverse_counter <= 0) {
clearInterval(downloadTimer);
}
},1000);
console.log(reverse_counter);
}
function stop_countdown(){
reverse_counter = 0;
document.getElementById('pbar').value = 0;
window.clearInterval(downloadTimer);
reverse_counter = 40;
}
function pause_countdown(){
window.clearInterval(downloadTimer);
}
</script>
Upvotes: 1
Reputation: 544
in order to stop any timer, you can use a global variable and name it whatever you want, so u can able to trigger and cancel the timer at any time. so I create a function that cancels the timer depending on that global variable as I mentioned before.
<progress value="0" max="40" id="pbar" ></progress>
<div id="start-stop">
<button id="start" onclick="start_countdown()">Start</button>
<button id="stop" onClick="clearinterval()">Stop</button>
</div>
var interval;
function start_countdown(){
var reverse_counter = 40;
interval= setInterval(function(){
document.getElementById('pbar').value = 40 - --reverse_counter;
if(reverse_counter <= 0)
clearInterval(interval);
},1000);
}
function clearinterval (){
clearInterval(interval);
}
Upvotes: 1