Convert "stopwatch" time to hourly - javascript

I have a stopwatch timer built in JS that counts up from 0 using hours, minutes, seconds and milliseconds. Currently when the user hits the stop button the value from the timer is appended to a hidden input element for form submission. I need to convert whatever the time is to just hourly to where it is appended to that hidden input. So right now if my clock is stopped at 25 minutes and 00 seconds, the value in the input is 00:25:00, I would like it to convert the time to something like .25 (for hours)
For example, for 30 minutes the value appended to my hidden input would be .5, for 45 minutes it would be .75, so on and so fourth.
Here is the stopwatch script, the Stop function is where the value is appended to our hidden input, just need to make sure it is converted to hourly
<script type="text/javascript">
var clsStopwatch = function () {
var startAt = 0;
var lapTime = 0;
var now = function () {
return (new Date()).getTime();
};
this.start = function () {
startAt = startAt ? startAt : now();
};
this.stop = function () {
lapTime = startAt ? lapTime + now() - startAt : lapTime;
startAt = 0;
};
this.time = function () {
return lapTime + (startAt ? now() - startAt : 0);
};
};
var x = new clsStopwatch();
var $time;
var clocktimer;
function pad(num, size) {
var s = "0000" + num;
return s.substr(s.length - size);
}
function formatTime(time) {
var h = m = s = ms = 0;
var newTime = '';
h = Math.floor(time / (3600 * 1000));
time = time % (3600 * 1000);
m = Math.floor(time / (60 * 1000));
time = time % (60 * 1000);
s = Math.floor(time / 1000);
ms = time % 1000;
newTime = pad(h, 2) + ':' + pad(m, 2) + ':' + pad(s, 2);
//newTime = pad(h, 2) + ':' + pad(m, 2) + ':' + pad(s, 2) + ':' + pad(ms, 2);
return newTime;
}
function show() {
$time = document.getElementById('time');
update();
}
function update() {
$time.innerHTML = formatTime(x.time());
}
function start() {
clocktimer = setInterval("update()", 1);
x.start();
}
function stop() {
x.stop();
document.getElementById('counter').value = formatTime(x.time());
clearInterval(clocktimer);
}
</script>

If I correctly understand what you need, this is your solution:
function millisecondsToHours(amountMS) {
return amountMS / 3600000;
}

Related

How can I make this js script so that it doesn't use eval?

I have this code
var clsStopwatch = function() {
var startAt = 0;
var lapTime = 0;
var now = function() {
return (new Date()).getTime();
};
this.start = function() {
startAt = startAt ? startAt : now();
};
this.stop = function() {
lapTime = startAt ? lapTime + now() - startAt : lapTime;
startAt = 0;
};
// Reset
this.reset = function() {
lapTime = startAt = 0;
};
// Duration
this.time = function() {
return lapTime + (startAt ? now() - startAt : 0);
};
};
var x = new clsStopwatch();
var $time;
var clocktimer;
function pad(num, size) {
var s = "0000" + num;
return s.substr(s.length - size);
}
function formatTime(time) {
var h = m = s = ms = 0;
var newTime = '';
h = Math.floor( time / (60 * 60 * 1000) );
time = time % (60 * 60 * 1000);
m = Math.floor( time / (60 * 1000) );
time = time % (60 * 1000);
s = Math.floor( time / 1000 );
ms = time % 1000;
newTime = pad(h, 2) + ':' + pad(m, 2) + ':' + pad(s, 2) + ':' + pad(ms, 3);
return newTime;
}
function show() {
$time = document.getElementById('time');
update();
}
function update() {
$time.innerHTML = formatTime(x.time());
}
function start() {
clocktimer = setInterval("update()", 1);
x.start();
}
function stop() {
x.stop();
clearInterval(clocktimer);
}
function reset() {
stop();
x.reset();
update();
}
Which runs a stopwatch.
My CSP conf has this unsafe-eval directive. It is insecure, so I removed it. And my code won't work and says in the console log that
clocktimer = setInterval("update()", 1);
is not allowed to run. How can I make it so that it can be run without the unsafe-eval directive?
I am unable to know what to do because I am really new to JS.
"update()" is just a string, and can't be called. You need to pass the function.
// Reference the function (probably better)
clocktimer = setInterval(update, 1)
// Call function with lambda (better in some situations, but not this one)
clocktimer = setInterval(() => update(), 1)

How can i reset my countdown and avoid multiple timer

I made a timer countdown in js. It runs after a click event. The issue is when i click again the timer doesn't reset and it creates another countdown but the former one still count. I would like to reset the first when i click again.
i tried to use a clear interval but i'm not sure to use it right.
function countdownto(target, time, callback) {
var finish = new Date(time);
var s = 1000,
m = s * 60,
h = m * 60,
d = h * 24;
(function timer() {
var now = new Date();
var dist = finish - now;
var days = Math.floor(dist / d),
hours = Math.floor((dist % d) / h),
minutes = Math.floor((dist % h) / m),
seconds = Math.floor((dist % m) / s);
var timestring = minutes + ' minute(s) ' + seconds + ' seconde(s)';
target.innerHTML = timestring
if (dist > 0) {
setTimeout(timer, 1000);
} else {
callback()
}
})()
}
var submitBtn = document.getElementById('yes');
submitBtn.addEventListener("click", function(e) {
// countdown element
var countdownel = document.getElementById('clockdiv');
// 20 min
var time = new Date()
time.setSeconds(time.getSeconds() + 1200)
// countdown function call
countdownto(countdownel, time, function() {
alert('end');
})
})
<button id="yes"></button>
<div><span id="clockdiv">countdown
</span></div>
You need to clear the last timeout on each click.
To do that create a global variable and assign the timeout into. After you can use clearTimeout on each click
See live demo
var timeout;
function countdownto(target, time, callback) {
var finish = new Date(time);
var s = 1000,
m = s * 60,
h = m * 60,
d = h * 24;
(function timer() {
var now = new Date();
var dist = finish - now;
var days = Math.floor(dist / d),
hours = Math.floor((dist % d) / h),
minutes = Math.floor((dist % h) / m),
seconds = Math.floor((dist % m) / s);
var timestring = minutes + ' minute(s) ' + seconds + ' seconde(s)';
target.innerHTML = timestring
if (dist > 0) {
timeout = setTimeout(timer, 1000);
} else {
callback()
}
})()
}
var submitBtn = document.getElementById('yes');
submitBtn.addEventListener("click", function(e) {
clearTimeout(timeout)
// countdown element
var countdownel = document.getElementById('clockdiv');
// 20 min
var time = new Date()
time.setSeconds(time.getSeconds() + 1200)
// countdown function call
countdownto(countdownel, time, function() {
alert('end');
})
})
<button id="yes">yes</button>
<div><span id="clockdiv">countdown
</span></div>
Note : You are simulate setInterval with setTimeout. I think it's better to use directly setInterval in your case
setTimeout(timer, 1000) returns internal timer ID. To stop the function you've passed in setTimeout() you have to stop the timer by calling clearTimeout(ID) function and pass internal timer ID you've got from setTimeout()
Also I recommend you to use setInterval():
var myVar = setInterval(myTimer, 1000);
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
to stop myTimer function clear myVar
clearTimeout(myVar);

Minutes not quite in sync with seconds

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/

Lost trying to create a stopwatch

I'm trying to self-taugh JavaScript and while doing some texts with a stopwatch I got lost into this problem. It's working but it's always starting on 95:34:47 instead of 00:00:00
This is what i tried so far.
<script>
/*Timer Stuff*/
function pad(num, size) {
var s = "0000" + num;
return s.substr(s.length - size);
}
function formatTime(time) {
var h = m = s = ms = 0;
var newTime = '';
h = Math.floor( time / (60 * 60 * 1000) );
time = time % (60 * 60 * 1000);
m = Math.floor( time / (60 * 1000) );
time = time % (60 * 1000);
s = Math.floor( time / 1000 );
ms = time % 1000;
newTime = pad(h, 2) + ':' + pad(m, 2) + ':' + pad(s, 2) + ':' + pad(ms, 3);
return newTime;
}
function update() {
var d = new Date();
var n = d.getTime();
document.getElementById("time").innerHTML = formatTime(n);
}
function start() {
MyVar = setInterval(update, 1);
}
</script>
</head>
<body>
<div>Time: <span id="time"></span></div>
<input type="button" value="start" onclick="start();">
</body>
I understand that I need to subtract an specific amount of time to match the timer accurately, however I can't figure out how to do it.
You need to store a variable with the start time, and subtract from that. The 95 you're getting for the hours is actually much higher, just being cropped, being that you're calculating from the Unix epoch.
I would just do it something like this:
function update() {
var d = new Date();
var n = d - startTime;
document.getElementById("time").innerHTML = formatTime(n);
}
function start() {
startTime = new Date();
MyVar = setInterval(update, 1);
}
Note that you don't even need to use d.getTime() when subtracting -- you can just subtract Date objects themselves.
You have to introduce a start-time variable.
In every update-step you have to get the difference from start to now.
For your code:
<script>
/*Timer Stuff*/
timestart = new Date();
timestart_time = timestart.getTime();
function pad(num, size) {
var s = "0000" + num;
return s.substr(s.length - size);
}
function formatTime(time) {
time = time -timestart_time;
var h = m = s = ms = 0;
var newTime = '';
h = Math.floor( time / (60 * 60 * 1000) );
time = time % (60 * 60 * 1000);
m = Math.floor( time / (60 * 1000) );
time = time % (60 * 1000);
s = Math.floor( time / 1000 );
ms = time % 1000;
newTime = pad(h, 2) + ':' + pad(m, 2) + ':' + pad(s, 2) + ':' + pad(ms, 3);
return newTime;
}
function update() {
var d = new Date();
var n = d.getTime();
document.getElementById("time").innerHTML = formatTime(n);
}
function start() {
MyVar = setInterval(update, 1);
}
</script>
</head>
<body>
<div>Time: <span id="time"></span></div>
<input type="button" value="start" onclick="start();">
</body>
That works for me :)

Objectify Javascript - How To Run A Javascript Function multiple Times

I have written a simple Javascript function (curteousy of codecall.net) that creates a count down timer.
It works fine when I run it, but I want to have more than one timer on the page.
When I place the function inside another div I get the numbers on the screen but only one of the last function actually counts down.
I have placed a link to the code here in JsFiddle which for one reason or another doesn't want to run it but it works. I just need multiple instances of it.
Any help is much appreciated, thanks in advance
The way you built it, all in the global namespace, makes it very difficult to incorporate two timers. Instead, you should just use a reusable object constructor. Demo here.
function Countdown(element, time) {
this.element = element;
this.time = time;
}
Countdown.time = function() {
return new Date().getTime() / 1000;
};
Countdown.formatRemaining = function(timeRemaining) {
function fillZero(n) {
return n < 10 ? '0' + n : n.toString();
}
var days = timeRemaining / 60 / 60 / 24 | 0;
var hours = timeRemaining / 60 / 60 | 0;
var minutes = timeRemaining / 60 | 0;
var seconds = timeRemaining | 0;
hours %= 24;
minutes %= 60;
seconds %= 60;
return days + ' day' + (days === 1 ? '' : 's') + ' ' + fillZero(hours) + ':' + fillZero(minutes) + ':' + fillZero(seconds);
};
Countdown.prototype.update = function() {
var timeRemaining = this.time + this.start - Countdown.time();
if(timeRemaining > 0) {
this.element.innerHTML = Countdown.formatRemaining(timeRemaining);
} else {
this.element.innerHTML = "Time's up!";
if(this.timer) {
clearInterval(this.timer);
this.timer = null;
}
}
};
Countdown.prototype.start = function() {
var countdown = this;
this.start = Countdown.time();
this.timer = setInterval(function() {
countdown.update();
}, 1000);
this.update();
};

Categories