I am working on a stopwatch and for now it works, but I want that I can calculate the average of time people get. E.g. let's say I have 5 times in an array which looks like the following: scores = ["00:32:192", "00:30:126", "00:31:542", "00:25:236", "00:36:320"];. You may think now: What the hell is it? Well the times are in: minutes:seconds:milliseconds. The array is printed to the screen by using a for loop.
jQuery
var int,
ms=0,
s=0,
m=0;
$('#swatch').text("00:00:00");
function swatch(){
var startTime = new Date().getTime();
int = setInterval(function(){
var time = new Date().getTime();
var dif = time-startTime;
ms= dif%1000;
s = Math.floor(dif/1000)%60;
m = Math.floor(dif/1000/60)%60;
if(ms < 10) {
ms = '0'+ms;
}
if(s < 10) {
s = '0'+s;
}
if(m < 10) {
m = '0'+m;
}
$('#swatch').text(m+':'+s+':'+ ms);
},1);
}
var scores= [];
$(document).on('keydown', function(e){
var result = $('#swatch').text();
var i = parseInt(scores.length);
if(e.keyCode == 32 && !int){
swatch();
} else if (e.keyCode == 32){
clearInterval(int);
int=0;
scores.push(result);
$('#score ol').append('<li>' + scores[i] + '</li>');
if(scores.length >= 5) {
$('#ao5').html("ao5: 00:27:43");
$('#ao5').slideDown(500);
}
if (scores.length >= 12) {
$('#ao12').html("ao12: 00:27:43");
$('#ao12').slideDown(500);
}
}
});
In my code above this, you see this:
if(scores.length >= 5) {
$('#ao5').html("ao5: 00:27:43");
$('#ao5').slideDown(500);
}
if (scores.length >= 12) {
$('#ao12').html("ao12: 00:27:43");
$('#ao12').slideDown(500);
}
I want if the array has 5 different time values (as in the example above where I showed you the array format) it outputs the average on the screen. As you see I just filled it in for myself to picture it, but I want a function that calculates it. I am building this in jQuery because the timer worked better in here than in JS.
If some of you guys could give me an example and re-write my code with the function in it, that'd be great. I am really struggling with this for days to figure out how I can calculate an average of 5 and/or 12.
Thank you.
Note that the code I provide below doesn't rely on JQuery or any library directly. You feed it an array of 'time-strings', and it gives you back an average. You can use whatever library you choose to get that array of strings.
First, you need a utility function which breaks a time-string into it's component pieces:
var str_to_time = function(time_str) {
var pieces =time_str.split(':');
return {
minutes: parseInt(pieces[0], 10),
seconds: parseInt(pieces[1], 10),
milliseconds: parseInt(pieces[2], 10)
};
};
Now a function to convert an array of time-strings to an array of times:
var str_array_to_time_array = function(str_array) {
return str_array.map(str_to_time);
};
Lastly, a way to average all these values together:
var average_time = function(time_array) {
var minutes = 0;
var seconds = 0;
var milliseconds = 0;
for (var i = 0; i < time_array.length; i++) {
minutes += time_array[i].minutes;
seconds += time_array[i].seconds;
milliseconds += time_array[i].milliseconds;
}
minutes /= time_array.length;
seconds /= time_array.length;
milliseconds /= time_array.length;
// Minutes and seconds may be fractional. Carry the fractions down.
seconds += (minutes - Math.floor(minutes)) * 60;
minutes = Math.floor(minutes);
milliseconds += (seconds - Math.floor(seconds)) * 1000;
seconds = Math.floor(seconds);
milliseconds = Math.round(milliseconds);
// if milliseconds is >= 1000, add a second.
seconds += Math.floor(milliseconds / 1000);
milliseconds %= 1000;
// If seconds >= 60, add a minute.
minutes += Math.floor(seconds / 60);
seconds %= 60;
return {
minutes: minutes,
seconds: seconds,
milliseconds: milliseconds
};
};
Now you can call something like the following to get an average:
average_time(str_array_to_time_array(['33:23:354', '34:00:32']))
// Object {minutes: 33, seconds: 41, milliseconds: 693}
Related
I have a timer that is counting down from a value that is being set by some user.
They enter some number which is being treated as minutes. number * 1000 * 60 to convert it into milliseconds - and from there the counter is counting down and decrements this number.
What I want to do is format this number as minutes and seconds so if the entered number is 3.5, it should be shown as 03:30.
I've tried using the date filter which is provided by Angular but it's not in sync with the value of the timer. It would decrement once and then stops.
Code:
<h4 class="timer">{{ vm.timer.ticks | date: "mm:ss"}}</h4>
The background for the timer is in a service
start(duration) {
this.ticks = duration;
this.timer = this.$interval(() => {
if (this.ticks === 0) return this.stop();
this.ticks--;
}, 1000);
}
I think it is because you are hiding "this" in your inner function. Try to rewrite it as (untested!):
start(duration) {
var ticks = duration;
this.timer = this.$interval(() => {
if (ticks === 0) return this.stop();
ticks--;
}, 1000);
}
Ok, so... I made a terrible mistake when I was calculating the time...
I set up $scope.$watch to watch over my variable from the service and according to that i was changing couple other variables.
$scope.$watch('vm.timer.ticks', value => {
if (value <= 0) {
vm.timer.count = 0;
vm.timer.latest = '';
}
if(vm.timer.ticks > 0) {
seconds = vm.timer.ticks % 60;
minutes = Math.floor(vm.timer.ticks / 60);
filledMinutes = minutes < 10 ? "0" + minutes : minutes;
filledSeconds = seconds < 10 ? "0" + seconds : seconds;
vm.displayTime = filledMinutes + ':' + filledSeconds;
} else {
vm.displayTime = '00:00';
}
});
I am trying to build an accurate countdown timer that shows mins and seconds left. I have tried 2 approaches. Approach 1 uses the setTimer function and calculates the drift. For that approach, some values get skipped and some values get repeated. Approach 2 yields all of the necessary values, but the values are not getting printed to the screen at even intervals (tested in repl.it). How can I make a timer that is both accurate and prints all of the values ?
Approach1:
function countTime(duration) {
var expected = 1;
var secsLeft;
var startT = new Date().getTime();
var oneSecond = 1000;
var expected = startT + oneSecond;
window.setTimeout(step, oneSecond);
function step() {
var nowT = new Date().getTime();
var drift = nowT - expected;
if (drift > oneSecond) {
console.log("drift is over 1 second long!");
}
console.log('drift is ' + drift);
var msDelta = nowT - startT;
var secsLeft = duration - Math.floor(msDelta / 1000);
console.log("secsLeft" + secsLeft);
if (secsLeft === 0) {
++count;
console.log("cleared");
} else {
expected += oneSecond;
setTimeout(step, Math.max(0, oneSecond - drift));
}
}
}
countTime(60);
Approach2:
function countTime(duration) {
var expected = 1;
var secsLeft;
var inter;
var startT = new Date().getTime();
inter = setInterval(function() {
//change in seconds
var sChange = Math.floor((new Date().getTime() - startT) / 1000);
if (sChange === expected) {
expected++;
secsLeft = duration - sChange;
console.log("seconds Left" + secsLeft);
}
if (secsLeft === 0) {
window.clearInterval(inter);
console.log("cleared");
}
}, 100);
}
countTime(60);
Consider using requestAnimationFrame.
function countTime(duration) {
requestAnimationFrame(function(starttime) {
var last = null;
function frame(delta) {
var timeleft = Math.floor(duration - (delta - starttime)/1000),
minutes = Math.floor(timeleft/60),
seconds = timeleft%60;
if( timeleft > 0) {
if( last != timeleft) {
console.log("Time left: "+minutes+"m "+seconds+"s");
last = timeleft;
}
requestAnimationFrame(frame);
}
}
frame(starttime);
});
}
countTime(60);
This will be precise to within the framerate of the browser itself :)
function(){
date = get the date
curSeconds = compute the number of seconds to be displayed
if(oldSeconds!=curSeconds) then refresh display and do oldSeconds = curSeconds;
}
Call this function quite often, the more you call it, the more accurate your timer will be. I advise you to use requestAnimationFrame() instead of setTimout() it will be called 60 times per second (period 16ms) since it is the refresh rate of most displays, it is the maximum visible "accuracy". Also it won't be called when page is not visible.
Simple, clean, no drift over long periods of time.
It also handle not being called for a while.
I am trying to display the time remaining for the next 5 minutes (snapped to the full 5 minutes of the current time e.g., 15:05, 15:10..)
I was able to achieve the same for the time remaining for next Hour (Not minutes):
<span class="timer"></span>
<script>
function secondPassed() {
var cur_date = new Date();
var hour = cur_date.getHours();
var minutes = cur_date.getMinutes();
var seconds = cur_date.getSeconds();
var minutes_remain = parseInt(59 - parseInt(minutes));
var seconds_remain = parseInt(60 - parseInt(seconds));
var timers = document.getElementsByClassName('timer');
for (var i = 0; i < timers.length; i++) {
timers[i].innerHTML = minutes_remain+":"+seconds_remain;
}
}
var countdownTimer = setInterval(secondPassed, 1000);
</script>
JSfiddle : http://jsfiddle.net/ov0oo5f7/
Something like this?
function secondPassed() {
var cur_date = new Date();
var minutes = cur_date.getMinutes();
var seconds = cur_date.getSeconds();
var timers = document.getElementsByClassName('timer');
for (var i = 0; i < timers.length; i++) {
timers[i].innerHTML = (4 - minutes % 5) + ":" + (seconds >= 50 ? "0" : "") + (59 - seconds);
}
}
var countdownTimer = setInterval(secondPassed, 1000);
<span class="timer"></span>
You can reduce the code a bit and to make it more accurate, use setTimeout and call the function as close as reasonable to the next full second. setInterval will slowly drift.
// Return the time to next 5 minutes as m:ss
function toNext5Min() {
// Get the current time
var secs = (new Date() / 1000 | 0) % 300;
// Function to add leading zero to single digit numbers
function z(n){return (n < 10? '0' : '') + n;}
// Return m:ss
return (5 - secs/60 | 0) + ':' + z(60 - (secs%60 || 60));
}
// Call the function just after the next full second
function runTimer() {
console.log(toNext5Min());
var now = new Date();
setTimeout(runTimer, 1020 - now % 1000);
}
The above ticks over on the full minute so that at say 10:00:00 it shows 5:00. If you'd rather is showed 0:00, then the last line of toNext5Min should be:
return (5 - (secs? secs/60 : 5) | 0) + ':' + z(60 - (secs%60 || 60));
This is what you need to change to get it to work the way you want:
var minutes = cur_date.getMinutes();
var seconds = cur_date.getSeconds();
try change it to this:
var minutes_remain = 5 - minutes%5 - 1;
var seconds_remain = 59 - seconds;
Try it out here: jsFiddle
Change your minutes remain to following line. It calculates current minute mod by 5 subtracted from 5, which is what you need.
function secondPassed() {
var cur_date = new Date();
var hour = cur_date.getHours();
var minutes = cur_date.getMinutes();
var seconds = cur_date.getSeconds();
var minutes_remain = parseInt(5 - parseInt(minutes%5));
var seconds_remain = parseInt(60 - parseInt(seconds));
var timers = document.getElementsByClassName('timer');
for (var i = 0; i < timers.length; i++) {
timers[i].innerHTML = minutes_remain+":"+seconds_remain;
}
}
var countdownTimer = setInterval(secondPassed, 1000);
Updated fiddle http://jsfiddle.net/ov0oo5f7/2/
You can work out what the next 5 minutes interval will be if you divide by 5, round it up, and multiply by 5 again.
You need to handle if you are on an exact minute otherwise minutes_remain will show as 1 minute less.
In terms of being accurate, you don't need to parseInt everywhere as they are all numbers already. I've tried to make it as efficient as possible. In any case, you are only checking it once a second, so you can't guarantee accuracy.
http://jsfiddle.net/ov0oo5f7/6/
function secondPassed() {
var cur_date = new Date();
var hour = cur_date.getHours();
// handle 0 seconds - would be 60 otherwise
var seconds_remain = 60 - (cur_date.getSeconds() || 60);
// handle ceil on 0 seconds - otherwise out by a minute
var minutes = cur_date.getMinutes() + (seconds_remain == 0 ? 0 : 1);
var minutes_remain = Math.ceil(minutes/5) * 5 - minutes;
var timers = document.getElementsByClassName('timer');
for (var i = 0; i < timers.length; i++) {
timers[i].innerHTML = minutes_remain+":"+seconds_remain;
}
}
var countdownTimer = setInterval(secondPassed, 1000);
If you are looking for the mechine time and counting it down for 5 minutes , then this might help -
var startTime = new Date();
function secondPassed() {
var cur_date = new Date();
if(parseInt((cur_date - startTime)/1000) >300 ){
window.clearInterval(countdownTimer);
}
var hour = cur_date.getHours();
var minutes = cur_date.getMinutes();
var seconds = cur_date.getSeconds();
var minutes_remain = parseInt(59 - parseInt(minutes));
var seconds_remain = parseInt(60 - parseInt(seconds));
var timers = document.getElementsByClassName('timer');
for (var i = 0; i < timers.length; i++) {
timers[i].innerHTML = minutes_remain+":"+seconds_remain;
}
}
var countdownTimer = setInterval(secondPassed, 1000);
A simple approach is nothing that 5 minutes are 5*60*1000 milliseconds, thus
var k = 5*60*1000;
var next5 = new Date(Math.ceil((new Date).getTime()/k)*k);
First off, sorry for any bad English as it's not my primary language.
I'm having some troubles with Javascript. A certain file keeps crashing my browser (doesn't matter if it's Chrome, Firefox or IE) after a few minutes.
$().ready(function() {
timeAgo();
});
function timeAgo() {
$('time.time-ago').each(function() {
//Get datetime from the attribute
var ago = $(this).attr('datetime');
//Split it so we can convert it to a Date object as Firefox doesn't allow raw input
var spl = ago.split(' ');
var date = spl[0].split('-');
var time = spl[1].split(':');
//Convert to object
ago = new Date(date[0],date[1]-1,date[2],time[0],time[1],time[2]);
//Get current date
var now = new Date();
//Calculate difference in days
var days = dayYear(now) - dayYear(ago);
if(days < 0) days += 365;
var out = '';
//Get the propper string
if(days > 0) {
if(days == 1) {
out = 'Gisteren';
}else if(days < 7) {
out = days +' dagen geleden';
}else if(days < 14) {
out = 'Een week geleden';
}else{
out = ago.toLocaleDateString('nl-nl',{day: "numeric",month: "short",year: "numeric"});
}
}else{
var dif = Math.round((now - ago)/1000);
if(dif < 10) {
out = 'Zojuist';
}else if(dif < 60) {
out = 'Enkele seconden geleden';
}else if(dif < 120) {
out = 'Een minuut geleden';
}else if(dif < 60 * 60) {
out = Math.floor(dif/60)+' minuten geleden';
}else if(dif < 60 * 60 * 2) {
out = 'Een uur geleden';
}else{
out = Math.floor(dif/60/60)+' uur geleden';
}
}
$(this).html(out);
});
setInterval(function(){timeAgo()},10000);
}
function dayYear(now) {
var first = new Date(now.getFullYear(),0,1);
var day = Math.round(((now - first) / 1000 / 60 / 60 /24) + 0.5);
return day;
}
I call it with for example the following code.
<time datetime="2013-05-12 19:12:15"></time>
Thanks in advance.
The reason is that you keep calling setInterval inside every loop.
You should use setTimeout instead (or only call setInterval once)
The difference is that setInterval executes the given every x milliseconds.
setTimeoutexecutes the given code after exactly x milliseconds (once).
Since you call setInterval inside the timeAgo method, after a while you will have a lot of timers running, all spawning new timers and the amount of timers will grow exponentially, eventually resulting in a crash.
I have a countdown like this one:
var countdown = {
startInterval: function() {
var count = 600
var countorig = 600;
var currentId = setInterval(function() {
var min = (count - (count % 60)) / 60;
var sec = count % 60;
if (sec < 10) {
$('#timer').html(min + ':0' + sec);
} else {
$('#timer').html(min + ':' + sec);
}
$('#time').val(countorig - count);
if (count == 0) {
$('#form').submit();
}--count;
}, 1000);
countdown.intervalId = currentId;
}
};
It works. But if I load the page, the countdown starts but it stutter it is not "round" like a clock is.
JSFiddle.
setInterval isn’t exact. You should use Dates instead, to get an accurate time, and then choose an interval of less than one second to get a smoother clock. Here’s a demo!
var countdown = {
startInterval: function() {
var count = 600;
var start = new Date(); // The current date!
var currentId = setInterval(function() {
var difference = Math.max(0, count - (new Date() - start) / 1000 | 0);
var min = difference / 60 | 0;
var sec = difference % 60;
$('#timer').text(min + ':' + (sec < 10 ? '0' : '') + sec);
$('#time').val(difference);
if(count === 0) {
$('#form').submit();
}
}, 200);
countdown.intervalId = currentId;
}
};
It's never a good idea to assume your timers are exact. Instead, use delta timing.
var startTime = new Date().getTime();
setInterval(function() {
var elapsed = new Date().getTime()-startTime;
console.log("Been running for "+Math.floor(elapsed/1000)+" seconds");
},25);
That is because setInterval is not meant to be a high resolution timer. It will NOT hit every 1000 milliseconds on the dot. You might have swings as much as 20 to 30 milliseconds in either direction, resulting in a clock that is off.
Using Date.now(), this is a quick example of a countdown function ( x is milliseconds )
function countdown(x){
var o = {future: Date.now()+x, last:-1, i:null}; // object so we can pass by-ref if req.
o.i = setInterval( function() { // use o.i so we can clear interval
var remain = o.future - Date.now(),
secs = Math.floor( remain / 1000 ),
mins = 0;
if( remain < 0 ){ // finished, do whatever
return clearInterval(o.i); // then clear & exit
}
if( secs === o.last ) return; // skip this iteration if it's not been a second
o.last = secs; // else update last time
// do whatever you want for this new second
if( secs > 59 ) mins = Math.floor( secs / 60 ), secs = secs % 60;
console.log(
(mins < 10 ? '0'+mins : mins) + ':' +
(secs < 10 ? '0'+secs : secs) + ' remain.'
);
}, 100);
}
If you know it wont be used in IE, consider adding o as an argument to the callback function in the interval and also as the last argument to setInterval (so it is passed to the callback as first arg), which means closure is independent => callback can be defined anywhere.