I'm working on a timer implementation that allows users to start the timer and pause or continue it whenever they want.
I faced a challenge when trying to pause the SVG animation.
I tried following this article, but it didn't work as expected.
Any suggestions?
CODE
(function() {
const btnStart = document.querySelector('.start'),
btnPause = document.querySelector('.pause'),
seconds = 60;
function formatTime(seconds) {
var sec = Math.floor(seconds % 60),
min = Math.floor(seconds / 60);
return min + ':' + (sec < 10 ? '0' + sec : sec);
}
function countdown(seconds) {
var tick = () => {
seconds--;
document.getElementById('time').innerHTML = formatTime(seconds);
};
tick();
var timer = setInterval(tick, 1000);
if (seconds <= 0) {
clearInterval(timer);
}
}
document.getElementById('time').innerHTML = formatTime(seconds);
btnStart.addEventListener('click', () => {
var gauge = document.querySelector('.timer-gauge');
countdown(seconds);
gauge.classList.add('ticking');
});
btnPause.addEventListener('click', () => {
var gauge = document.querySelector('.timer-gauge');
gauge.classList.toggle('paused');
});
}());
* {
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
// CSS styles here...
CODE
After implementing some changes based on this answer, the animation became inconsistent; speeding up in the middle and slowing down at the beginning and end. This affects its synchronization with the "clock" visual representation.
(function() {
const btnStart = document.querySelector('.start'),
btnPause = document.querySelector('.pause'),
seconds = 60;
function formatTime(seconds) {
var sec = Math.floor(seconds % 60),
min = Math.floor(seconds / 60);
return min + ':' + (sec < 10 ? '0' + sec : sec);
}
function countdown(seconds) {
var tick = () => {
seconds--;
document.getElementById('time').innerHTML = formatTime(seconds);
};
tick();
var timer = setInterval(tick, 1000);
if (seconds <= 0) {
clearInterval(timer);
}
}
document.getElementById('time').innerHTML = formatTime(seconds);
btnStart.addEventListener('click', () => {
var gauge = document.querySelector('.timer-gauge');
countdown(seconds);
gauge.classList.add('ticking');
});
btnPause.addEventListener('click', () => {
var gauge = document.querySelector('.timer-gauge');
gauge.classList.toggle('paused');
});
}());
* {
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
// More CSS styles here...