I've written a timer method which isn't working correctly. It is supposed to display the time elapsed while on a form, but it is counting by 2's or 3's instead of once per second. What could cause this behavior and how can I fix it?
My code:
function startTimer() {
var minutes, seconds;
setInterval(function () {
if (!isPaused) {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
$('#TimeLabel').text("Form Time: " + minutes + ":" + seconds);
++timer;
}
}, 1000);
}
The above code displays "Form Time: 00:01" then "Form Time: 00:04" then "Form Time:00:07" ect.
Here's an example of what I came up with. It uses time so as not to be dependent on the accuracy of your setInterval. Hope this helps!
function startTimer(){
var minutes,
seconds;
var startTime = new Date;
setInterval(function(){
var currentTime = new Date;
seconds = currentTime.getSeconds() - startTime.getSeconds();
if(seconds < 0){
seconds += 60;
}else if(seconds === 0){
minutes = currentTime.getMinutes() - startTime.getMinutes();
}
console.log(minutes + ':' + seconds);
}, 100);
}
startTimer();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With