Minutes not quite in sync with seconds - javascript

I have a timer which I am testing, it seems there is a bit of drift between when the minute countdown goes down by 1 and seconds whenever it reaches 59 seconds ()ie every minute:-
How can I alter this so they are both in sync?
my code is the following:-
$(document).ready(function() {
function now() {
return window.performance ? window.performance.now() : Date.now();
}
function tick() {
var timeRemaining = countdown - ((now() - initTick) / 1000);
timeRemaining = timeRemaining >= 0 ? timeRemaining : 0;
var countdownMinutes = Math.floor(timeRemaining / 60);
var countdownSeconds = timeRemaining.toFixed() % 60;
countdownTimer.innerHTML = countdownMinutes + ":" + countdownSeconds;
if (countdownSeconds < 10) {
countdownTimer.innerHTML = countdownMinutes + ":" + 0 + countdownSeconds;
}
if (timeRemaining > 0) {
setTimeout(tick, delay);
}
}
var countdown = 600; // time in seconds until user may login again
var delay = 20; // time (in ms) per tick
var initTick = now(); // timestamp (in ms) when script is initialized
var countdownTimer = document.querySelector(".timer"); // element to have countdown written to
setTimeout(tick, delay);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="timer"></div>
js fiddle: https://jsfiddle.net/robbiemcmullen/cer8qemt/1/

The issue is the precision is not the same for minutes and seconds.
You need to round to the nearest second before /60 / %60.
Consider: exactly 9 mins remaining:
var x = 540;
console.log(x.toFixed() % 60, Math.floor(x / 60));`
Output is: (0,9)
Then consider the call 20 ms later:
var x = 539.980;
console.log(x.toFixed() % 60, Math.floor(x / 60));
the output is now: (0, 8).
So the seconds haven't changed (yet) but the minute does.

Here is a version using setInterval and removing the use of .toFixed ()
Why do you use an interval of 20ms and not 1 second?
//method for countdown timer
$(document).ready(function() {
function now() {
return window.performance ? window.performance.now() : Date.now();
}
function tick() {
var timeRemaining = countdown - elapsedTime;
var countdownMinutes = Math.floor(timeRemaining / 60);
var countdownSeconds = timeRemaining % 60;
countdownTimer.innerHTML = countdownMinutes + ":" + countdownSeconds;
if (countdownSeconds < 10) {
countdownTimer.innerHTML = countdownMinutes + ":" + 0 + countdownSeconds;
}
++elapsedTime;
return timeRemaining;
}
var countdown = 600;
var elapsedTime = 0;
var timeRemaining;
// countdown: time in seconds until user may login again
//var delay = 20;
// delay: time (in ms) per tick
var initTick = now(); // initTick: timestamp (in ms) when script is initialized
var countdownTimer = document.querySelector(".timer");
// countdownTimer: element to have countdown written to
var interval = setInterval(function() {
if(tick() <= 0) {
clearInterval(interval);
}
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="timer"></div>
js fiddle https://jsfiddle.net/ud3wm8t1/

Related

Javascript Countdown timer using SQL variable

I am new to javascript/jquery. I found the following example on the internet and I am trying to get it working with my SQL variable. But I am stuck because all it does is count down from 60 over and over again..
What I am trying to accomplish is the following. I have a variable which says how many seconds a user needs to wait before it can perform the action again $secs. What I need is to have the time and process-bar countdown with the seconds from the variable to zero. After that I will add a page reload line to it. But first the timer needs to work. I would really appreciate any help as I can not find any workable solution/explanation for my problem.
<div id='timer'></div>
<div id='progress' style='background:red; height:5px;'></div>
<script>
function started(duration) {
var TotalSeconds = "<?php echo $secs; ?>";
var documentWidth = $(document).width();
var start = Date.now();
var intervalSetted = null;
function timer() {
var diff = duration - (((Date.now() - start) / 1000) | 0);
var seconds = (diff % 60) | 0;
seconds = seconds < 10 ? "0" + seconds : seconds;
$('#timer').html("00:" + seconds);
var progresBarWidth = (seconds * documentWidth / TotalSeconds);
$('#progress').css({
width: progresBarWidth + 'px'
});
if (diff <= 0) {
clearInterval(intervalSetted);
}
}
timer();
intervalSetted = setInterval(timer, 1000);
}
started("<?php echo $secs; ?>");
</script>
You need to convert duration to time format.
<div id='timer'></div>
<div id='progress' style='background:red; height:5px;'></div>
<script>
function started(duration) {
var TotalSeconds = duration;
var documentWidth = $(document).width();
var start = Date.now();
var intervalSetted = null;
function timer() {
var diff = duration - (((Date.now() - start) / 1000) | 0);
var seconds = (diff % duration) | 0;
seconds = seconds < 10 ? "0" + seconds : seconds;
var date = new Date(0);
date.setSeconds(seconds);
var timeString = date.toISOString().substr(11, 8);
$('#timer').html(timeString);
var progresBarWidth = (seconds * documentWidth / TotalSeconds);
$('#progress').css({
width: progresBarWidth + 'px'
});
if (diff <= 0) {
clearInterval(intervalSetted);
}
}
timer();
intervalSetted = setInterval(timer, 1000);
}
started("<?php echo $secs; ?>");
</script>
function started(duration) {
var TotalSeconds = duration;
var documentWidth = $(document).width();
var start = Date.now();
var intervalSetted = null;
function timer() {
var diff = duration - (((Date.now() - start) / 1000) | 0);
var seconds = (diff % duration) | 0;
seconds = seconds < 10 ? "0" + seconds : seconds;
var date = new Date(0);
date.setSeconds(seconds);
var timeString = date.toISOString().substr(11, 8);
$('#timer').html(timeString);
var progresBarWidth = (seconds * documentWidth / TotalSeconds);
$('#progress').css({
width: progresBarWidth + 'px'
});
if (diff <= 0) {
clearInterval(intervalSetted);
}
}
timer();
intervalSetted = setInterval(timer, 1000);
}
started(60);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='timer'></div>
<div id='progress' style='background:red; height:5px;'></div>

Timer - javascript

I have a problem with a timer in below function. How to change seconds for a minute and seconds? In present function, the timer counting only seconds and milliseconds.
if (timer === 1) {
var startTime = Date.now();
the_timer = setInterval(function() {
var elapsedTime = Date.now() - startTime;
finished_time = (elapsedTime / 1000).toFixed(3);
$("#timer").text(finished_time);
}, 44);
}
The function getTimeStr does this. It even formats it nicely so 3 seconds will be displayed as 0:03, 32 as 0:32 and 71 seconds as 1:11.
function getTimeStr(milliseconds) {
var minutes = milliseconds / 60000;
var intMinutes = Math.floor(minutes);
var seconds = Math.floor((minutes - intMinutes) * 60);
return intMinutes + ':' + (seconds < 10 ? ('0' + seconds.toFixed(0)) : seconds.toFixed(0));
}
var startTime = new Date();
setInterval(function() {
var elapsedTime = Date.now() - startTime;
console.log(getTimeStr(elapsedTime));
}, 100);

How to initialize a countdown timer to reflect the user input

I'm creating a countdown timer based on a users input. When the user pauses and resumes, the timer restarts at the initial inputed value and fails to resume from the current interval. I've uploaded the code into Codepen.
http://codepen.io/alivera/pen/JGpvRx
//Timer
var myTimer;
var duration = sessionCounter * 60;
var startTimer = function() {
minutes = parseInt(duration / 60);
seconds = parseInt(duration % 60);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
document.getElementById("clockTimer").innerHTML = minutes + ":" + seconds;
if (--duration < 0) {
document.getElementById("toggleStatus").innerHTML = "<br>Break!";
}
};
//Start Timer
var go = function() {
myTimer = setInterval(startTimer, 1000);
document.getElementById('start').innerHTML = "Stop";
document.getElementById('start').className = "btn btn-danger";
document.getElementById("start").onclick = stop;
};
//Stop Timer
var stop = function() {
clearInterval(myTimer);
document.getElementById('start').innerHTML = "Start";
document.getElementById('start').className = "btn btn-success";
document.getElementById("start").onclick = go;
};
duration.onload = stop();
You're loading the time to count down from from the #clockTimer element:
var sessionCounter = document.getElementById("clockTimer").innerHTML;
This is bad because the contents of that element are changing. Often.
And parseInt on the next line only is only giving you the number before the colon. Your best bet for solving this problem would be storing the current time remaining and the previously set time in separate variables, as I have done below.
Your code was a little difficult to work with, so while correcting the error(s), I ended up almost completely rewriting it.
Here's my version; I'll explain it line-by-line (or section-by-section, or whatever):
First, put all of our elements in to easy-to-use (and type) variables:
var subBreakButton = document.getElementById("subBreakButton"),
breakTimer = document.getElementById("breakTimer"),
addBreakButton = document.getElementById("addBreakButton"),
subSessionButton = document.getElementById("subSessionButton"),
sessionTimer = document.getElementById("sessionTimer"),
addSessionButton = document.getElementById("addSessionButton"),
breakSession = document.getElementById("breakSession"),
clockTimer = document.getElementById("clockTimer"),
These variables are in seconds (thus m * s):
breakLength = 5 * 60, // Minutes to seconds
sessionLength = 25 * 60, // Minutes to seconds
sessionTimeLeft = sessionLength;
Next, a helper method that formats times into a mm:ss ... format:
function timeString (seconds) {
var minutes = parseInt(seconds / 60) + "",
seconds = parseInt(seconds % 60) + "";
if (minutes.length === 1)
minutes = "0" + minutes;
if (seconds.length === 1)
seconds = "0" + seconds;
return minutes + ":" + seconds;
}
Third, event listeners for the plus and minus buttons:
// Event Listeners
addBreakButton.addEventListener("click", function () {
breakLength += 1 * 60;
breakTimer.innerHTML = timeString(breakLength);
});
subBreakButton.addEventListener("click", function () {
breakLength -= 1 * 60;
if (breakLength < 0)
breakLength = 0;
breakTimer.innerHTML = timeString(breakLength);
});
addSessionButton.addEventListener("click", function () {
sessionLength += 1 * 60;
sessionTimer.innerHTML = timeString(sessionLength);
});
subSessionButton.addEventListener("click", function () {
sessionLength -= 1 * 60;
if (sessionLength < 0)
sessionLength = 0;
sessionTimer.innerHTML = timeString(sessionLength);
});
And, the fun part:
// Timer
var myTimer;
function startTimer () {
if (myTimer) // Check to see if a timer was already running, and if so, stop it
stopTimer();
sessionTimeLeft = sessionLength;
myTimer = setInterval(function () {
sessionTimeLeft--;
if (sessionTimeLeft <= 0) {
sessionTimeLeft = 0;
stopTimer();
}
clockTimer.innerHTML = (sessionTimeLeft <= 0? "Break!": timeString(sessionTimeLeft));
}, 1000);
}
function stopTimer () {
clearInterval(myTimer);
myTimer = 0;
}
Lastly, wrappers:
// Start Timer
function go() {
startTimer();
}
//Pause Timer
function stop() {
stopTimer();
}
Codepen: http://codepen.io/anon/pen/ZQjLZE?editors=1010

Showing milliseconds in a timer html [duplicate]

This question already has answers here:
Adding milliseconds to timer in html
(2 answers)
Closed 8 years ago.
How do i show a countdown timer in html?
Current code:
var count=6000;
var counter=setInterval(timer, 1);; //1000 will run it every 1 second
function timer(){
count=count-1;
if (count <= 0){
clearInterval(counter);
return;
}
document.getElementById("timer").innerHTML=count + " milliseconds"; // watch for spelling
}
Converting seconds to ms
function msToTime(s) {
var ms = s % 1000;
s = (s - ms) / 1000;
var secs = s % 60;
s = (s - secs) / 60;
var mins = s % 60;
var hrs = (s - mins) / 60;
return hrs + ':' + mins + ':' + secs + '.' + ms;
}
How would i call out the timer?
still shows the timer as ms. i want it to show up as 99:00 seconds instead of 9900 milliseconds.
Thanks
You can do something like this:
var expires = new Date();
expires.setSeconds(expires.getSeconds() + 60); // set timer to 60 seconds
var counter = setInterval(timer, 1);
function timer() {
var timeDiff = expires - new Date();
if (timeDiff <= 0) {
clearInterval(counter);
document.getElementById("timer").innerHTML = "00:00";
return;
}
var seconds = new Date(timeDiff).getSeconds();
var milliSeconds = (new Date(timeDiff).getMilliseconds() / 10).toFixed(0);
var seconds = seconds < 10 ? "0" + seconds : seconds;
var milliSeconds = milliSeconds < 10 ? "0" + milliSeconds : milliSeconds;
document.getElementById("timer").innerHTML = seconds + ":" + milliSeconds; // watch for spelling
}
Here i set the start time from the javascript Date() function and then calculate the difference from current time in the timer() function.
Check it out here: JSFiddle
If it's JavaScript and has to do with Time I use moment.js
http://momentjs.com
Moment defaults to milliseconds as it's first parameter:
moment(9900).format("mm:ss"); Is 9 seconds, displayed as: 00:09
http://plnkr.co/edit/W2GixF?p=preview
Here's an actually accurate timer (in that it actually shows the correct amount of time left). setInterval will never call every 1 ms regardless of what you ask for because the actually resolution isn't that high. Nor can you rely on consistency because it's not running in a real-time environment. If you want to track time, compare Date objects:
var count=60000;
var start = new Date();
var counter=setInterval(timer, 1); //1000 will run it every 1 second
function timer(){
var left = count - (new Date() - start);
if (left <= 0){
clearInterval(counter);
document.getElementById("timer").innerHTML = msToTime(0) + " seconds";
return;
}
document.getElementById("timer").innerHTML = msToTime(left) + " seconds"; // watch for spelling
}
function msToTime(s) {
var ms = s % 1000;
s = (s - ms) / 1000;
return s + ':' + pad(ms, 3);
}
function pad(n, width, z) {
z = z || '0';
n = n + '';
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
<div id='timer'></div>
Borrowing from #Cheery's fiddle as a starting point.

javascript countdown to next real 5 minutes

I need to create a javascript timer that will count down to the next 5 minutes.
For example let's say the time is 00:07:30, the time will say 02:30
if the time is 15:42:00 the timer will say 03:00
I can't really think of any good way to du this.
thank you.
There are many ways to do this. My idea is to find out the reminder of current time divide by five minutes (300 seconds).
Demo : http://jsfiddle.net/txwsj/
setInterval(function () {
var d = new Date(); //get current time
var seconds = d.getMinutes() * 60 + d.getSeconds(); //convet current mm:ss to seconds for easier caculation, we don't care hours.
var fiveMin = 60 * 5; //five minutes is 300 seconds!
var timeleft = fiveMin - seconds % fiveMin; // let's say now is 01:30, then current seconds is 60+30 = 90. And 90%300 = 90, finally 300-90 = 210. That's the time left!
var result = parseInt(timeleft / 60) + ':' + timeleft % 60; //formart seconds back into mm:ss
document.getElementById('test').innerHTML = result;
}, 500) //calling it every 0.5 second to do a count down
Instead you could try using window.setInterval() like this:
window.setInterval(function(){
var time = document.getElementById("secs").innerHTML;
if (time > 0) {
time -= 1;
} else {
alert ("times up!");
//or whatever you want
}
document.getElementById("secs").innerHTML = time;
}, 1000);
const startMinutes = 1
let time = startMinutes * 60
const updateCountDown = () => {
const t = setInterval(() => {
const minutes = Math.floor(time / 60)
const seconds = time % 60
const result = `${parseInt(minutes)}:${parseInt(seconds)}`
document.getElementById('test').innerHTML = result
time--
if (minutes === 0 && seconds === 0) {
clearInterval(t)
}
}, 1000)
}
If you want to do a timer on your webpage, you can try to use something like this:
<html>
<head>
<script type="text/javascript">
var now = new Date().getTime();
var elapsed = new Date().getTime() - now;
document.getElementById("timer").innerHtml = elapsed;
if (elapsed > 300000 /*milliseconds in 5 minutes*/) {
alert ("5 minutes up!");
//take whatever action you want!
}
</script>
</head>
<body>
<div id="timer"></div>
</body>
</html>

Categories