Reputation: 432
I have to stop a timer and an animation of a bar which width is decreasing dependently on a time variable and then resume both if pressed a button, so that the bar animation will continue from where it stopped and the same for the timer. How can I do that?
I can execute a function on button press, it's just the stopping and resuming functions that I don't know.
$("#timebar")
is the animated bar.
function startTimer() {
timer = setTimeout(function(){
barAnimation();
}, time);
}
function stopTimer() {
$('#timebar').stop();
$('#timebar').css("width","100%");
clearTimeout(timer);
}
function barAnimation() {
$("#timebar").animate({ width: "0%" }, time, "linear");
}
Upvotes: 0
Views: 1069
Reputation: 5472
I think something like this is what you're looking for:
var time = 0;
var remaining = 15000;
var interval;
$('#start').click(startTimer);
$('#stop').click(stopTimer);
function startTimer() {
if (!interval) {
interval = setInterval(function(){
if (remaining % 1000 === 0)
$('#time').html(time++);
remaining -= 100;
}, 100); // 100 w/ modulo instead of 1000 for better precision
barAnimation();
}
}
function stopTimer() {
$('#timebar').stop();
clearInterval(interval);
interval = false;
}
function barAnimation() {
$("#timebar").animate({ width: "0%" }, remaining, "linear");
}
#timebar {
background-color: black;
width: 100%;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="start">Start</button>
<button id="stop">Stop</button>
<div id="time">0</div>
<div id="timebar"></div>
Upvotes: 0
Reputation: 9782
This doesn't have the animation, but it does offer a start/stop and progress indicator.
var time = 0;
var timer = 0;
var running = false;
function startTimer() {
running = true;
timer = setInterval(function() {
barAnimation();
}, 1000);
}
function stopTimer() {
running = false;
clearInterval(timer);
}
function barAnimation() {
time++;
$("#count").text(time);
$("#timebar").prop("value", time);
}
$("#go").on("click", function(evt) {
if (running) {
stopTimer();
} else {
startTimer();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="go">Go</button>
<progress id="timebar" value="0" max="100"></progress>
<div id="count"></div>
Upvotes: 1