Stopwatch doesn't add zero when there is a one-digit number - javascript

I would like to make the time display that time 01: 02: 03:43, but I get 0:0:00000000000000001:15 I tired add 0 in dev **0:0:0:0, but it doesn't work. Is it good code for timer?
var hour = 0;
var min = 0;
var sec = 0;
var miliSec = 0;
var timer;
function callTimer() {
miliSec++;
if (miliSec < 100) {
if (miliSec === 99) {
miliSec = 0;
sec++;
if (sec === 60) {
sec = 0;
min++;
if (min === 60) {
min = 0;
hour++
}
}
}
} else {
miliSec = 0;
}
document.getElementById("#timer").innerHTML = hour + ":" + min + ":" + sec + ":" + miliSec;
}
function start() {
document.getElementById("#start").disabled = true;
timer = setInterval(callTimer, 10);
}
function stop() {
document.getElementById("#start").disabled = false;
clearInterval(timer);
}
function reset() {
stop();
hour = 0;
min = 0;
sec = 0;
miliSec = 0;
document.getElementById("#timer").innerHTML = hour + ":" + min + ":" + sec + ":" + miliSec;
}
I have to give more details about this problem, because validation don't allow post me that problem. Well I wrote this ;)

I added toString().padStart(2, "0") to each element.
You can read more about padStart() here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
var hour = 0;
var min = 0;
var sec = 0;
var miliSec = 0;
var timer;
function callTimer() {
miliSec++;
if (miliSec < 100) {
if (miliSec === 99) {
miliSec = 0;
sec++;
if (sec === 60) {
sec = 0;
min++;
if (min === 60) {
min = 0;
hour++
}
}
}
} else {
miliSec = 0;
}
/* Add 0 every time -- This does not work because it changes the type from a number to string, causing the unexpected behavior
if (sec < 10) {
sec = "0" + sec;
}else{
sec;
}
*/
document.getElementById("#timer").innerHTML = hour.toString().padStart(2, "0") + ":" + min.toString().padStart(2, "0") + ":" + sec.toString().padStart(2, "0") + ":" + miliSec;
}
function start() {
document.getElementById("#start").disabled = true;
clearInterval(timer);//stop any previous interval before starting another
timer = setInterval(callTimer, 10);
}
function stop() {
document.getElementById("#start").disabled = false;
clearInterval(timer);
}
function reset() {
stop();
hour = 0;
min = 0;
sec = 0;
miliSec = 0;
document.getElementById("#timer").innerHTML = hour.toString().padStart(2, "0") + ":" + min.toString().padStart(2, "0") + ":" + sec.toString().padStart(2, "0") + ":" + miliSec;
}
<nav class="controls">
START
STOP
CLEAR
</nav>
<div id="#timer">00:00:00:0</div>

Instead of keeping four counters, you could very easily get the delta in milliseconds on every run of the callTimer callback and then do a few simple calculations to get seconds, hours, weeks... whatever the time units you may need. Something along these lines should do the trick:
var startTS
function formatNumber(num, digits) {
return `000${num}`.slice(-digits) // Get last X digits (in our case will be either 2 or 3)
}
function callTimer() {
const currentTS = Date.now()
const elapsed = currentTS - startTS // Elapsed time in milliseconds
const elapsedSec = Math.floor(elapsed/1000) // Whole seconds
const elapsedMin = Math.floor(elapsedSec/60) // Whole minutes
const elapsedHr = Math.floor(elapsedMin/60) // Whole hours
...
const msec = elapsed % 1000 // Get the "milliseconds" part
const sec = elapsedSec % 60 // Seconds part
const min = elapsedMin % 60 // Minutes
const hr = elapsedHr % 60 // Hours
const fmtStr = `${formatHumber(hr,2)}:${formatNumber(min,2)}:${formatNumber(sec,2)}.${formatNumber(msec,3)}`
document.getElementById("#timer").innerHTML = fmtStr
}
...
function start() {
document.getElementById("#start").disabled = true;
startTS = Date.now()
timer = setInterval(callTimer, 10);
}
...
Hope that helps!

Related

Javascript stopwatch not reliably stopping

I have a stopwatch controlled by pressing space which looks something like this:
let startTime;
let stopTime;
let timerStatus = 0;
let timePassed;
let interval;
window.onkeyup = function(event) {
if(event.keyCode == 32) {
if(timerStatus == 0) {
start();
display();
} else if(timerStatus == 2) {
timerStatus = 0;
}
}
}
window.onkeydown = function(event) {
if(event.keyCode == 32) {
if(timerStatus == 1) {
stop();
} else if(timerStatus == 0) {
$("#time").html("0.00");
}
}
}
function start() {
let d = new Date();
startTime = d.getTime();
timerStatus = 1;
}
function stop() {
let d = new Date();
stopTime = d.getTime();
clearInterval(interval);
timerStatus = 2;
}
function display() {
interval = setInterval(function() {
let now = Date.now();
timePassed = now - startTime;
let seconds = Math.floor(timePassed / 1000);
let minutes = Math.floor(timePassed / 60000);
let milliseconds = timePassed % 1000;
//getting rid of third decimal place
milliseconds = milliseconds.toString().slice(0, -1);
parseFloat(milliseconds);
console.log(milliseconds);
let time = minutes + ":" + seconds + "." + milliseconds;
if(milliseconds < 10) milliseconds = "0" + milliseconds;
if(milliseconds < 1) milliseconds = "0" + milliseconds;
if(minutes < 1) {
time = seconds + "." + milliseconds;
}
$("#time").html(time);
}, 10);
}
<h1 id='time'>0.00</h1>
This works just fine, apart from the fact that sometimes when pressing space to stop the stopwatch, it will instead stop and then immediately start the stopwatch again. Often after this happens once, you then can't ever stop the stopwatch until the page is reloaded.
Any help would be greatly appreciated.
Thanks.

Formatting a time as string

I wrote this easy JS timer and i have problem with if for minutes, it still writing in first sec 00:01, second sec 000:02...... If you understand me. Please can you help me? Thank you
var sec = 0;
var min = 0;
var time;
function timer() {
sec++;
if (sec < 10) {
sec = "0" + sec;
}
if (min < 10) { //here is problem I think
min = "0" + min;
}
if (sec == 60) {
sec = 0;
min++;
}
if (sec == 5) { //this is just a function test
document.getElementById("myForm").submit();
}
document.getElementById("myTimer").innerHTML = min + ":" + sec;
}
function start() {
time = setInterval("timer()", 1000);
}
Each time your function runs, it adds a zero to the beginning of min, which is a global variable. That's why it works the way it does.
You could use a temporary variable for holding the time as string.
var sec = 0;
var min = 0;
var time;
function timer() {
sec++;
var minStr = (min < 10) ? '0' + min : '' + min;
var secStr = (sec < 10) ? '0' + sec : '' + sec;
document.getElementById("myTimer").innerHTML = minStr + ":" + secStr;
}
function start() {
time = setInterval("timer()", 1000);
}
start();
<div id="myTimer"></div>

Cannot read property 'parentNode' of null. Error i get in console

var button1 = document.getElementById("start");
var button2 = document.getElementById("stop");
var timegraph = document.getElementById("ceas");
var lapButton = document.getElementById("lap");
var lame = document.getElementById("test");
var time = 0;
var ResetStart = 0;
var myInterval;
var body = document.getElementById("body");
var action = document.getElementById("lappara");
function Start() {
if (ResetStart == 0) {
ResetStart = 1;
Running();
button1.innerHTML = "Pause";
}
else {
ResetStart = 0;
button1.innerHTML = "Resume";
clearInterval(myInterval);
}
}
function Reset() {
time = 0;
ResetStart = 0;
button1.innerHTML = "Start";
timegraph.innerHTML = "00:00:00:00";
clearInterval(myInterval);
var aux = action.parentNode;
aux.removeChild(action);
}
function OnGoing() {
time++;
var hours = Math.floor(time / 100 / 60 / 60);
var minutes = Math.floor(time / 100 / 60 % 60);
var seconds = Math.floor(time / 100 % 60);
var hundreds = Math.floor(time / 10 % 10);
var thousands = time % 10;
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
timegraph.innerHTML = hours + ":" + minutes + ":" + seconds + ":" + hundreds + thousands;
}
function Running() {
if (ResetStart == 1) {
myInterval = setInterval(OnGoing, 10);
}
else {
timegraph.innerHTML = "00:00:00:00";
}
}
function Lap() {
var n = document.createElement("p");
n.setAttribute("id", "lappara");
var text = document.createTextNode(timegraph.innerHTML);
n.appendChild(text);
body.insertBefore(n, action);
}
Whenever i call the Reset() function i get the error above. This code is supposed to be a stopwatch and the Lap() function just creates laps. I looked up some solutions but none seemed to work. Please help me if you can
I assume you can call Reset() once but next time you call it the error appears. This is because of aux.removeChild(action). You delete action and then you try to get it's parentNode - that's where the problem is.
I think you call func Reset() before create element with id lappara by lap() func or call Reset() function several times.

JavaScript timer doesn't start after being reset

The timer, start/pause button and reset button all work as expected.
The only bug it seems to have is, when I run the timer and reset it, it
won't start again. Only after I press the Start/Pause button 2 times it will run again.
Live demo: http://codepen.io/Michel85/full/pjjpYY/
Code:
var timerTime;
var time = 1500;
var currentTime;
var flag = 0;
var calculateTime
// Start your Timer
function startTimer(time) {
document.getElementById("btnUp").disabled = true;
document.getElementById("btnDwn").disabled = true;
timerTime = setInterval(function(){
showTimer();
return flag = 1;
}, 1000);
}
// Reset function
function resetTimer(){
clearInterval(timerTime);
document.getElementById('showTime').innerHTML=(calculateTime(1500));
document.getElementById("btnUp").disabled = false;
document.getElementById("btnDwn").disabled = false;
return time=1500;
}
// Pause function
function pauseTimer(){
clearInterval(timerTime);
currentTime = time;
document.getElementById('showTime').innerHTML=(calculateTime(time));
return flag = 0;
}
// Update field with timer information
function showTimer(){
document.getElementById("showTime").innerHTML=(calculateTime(time));
flag = 1;
if(time < 1){
resetTimer();
}
time--;
};
// Toggle function (Pause/Run)
function toggleTimmer(){
if(flag == 1){
pauseTimer();
} else {
startTimer();
}
}
/*
Round-time up or down
*/
// Set timer Up
function timeUp(){
time += 60;
document.getElementById("showTime").innerHTML=(calculateTime(time));
return time;
}
// Set timer Down
function timeDown(){
if(time > 60){
time-=60;
}
document.getElementById("showTime").innerHTML=(calculateTime(time));
return time;
}
/*
Break-time up down
*/
// Set timer Up
function breakUp(){
time += 60;
document.getElementById("showTime").innerHTML=(calculateTime(time));
return time;
}
// Set timer Down
function breakDown(){
if(time > 60){
time-=60;
}
document.getElementById("showTime").innerHTML=(calculateTime(time));
return time;
}
// Calculate the Days, Hours, Minutes, seconds and present them in a digital way.
function calculateTime(totalTime) {
// calculate days
var days = Math.floor(totalTime / 86400);
totalTime = totalTime % 86400
// calculate hours
var hours = Math.floor(totalTime / 3600);
totalTime = totalTime % 3600;
// calculate minutes
var minutes = Math.floor(totalTime / 60);
totalTime = totalTime % 60;
// calculate seconds
var seconds = Math.floor(totalTime);
function convertTime(t) {
return ( t < 10 ? "0" : "" ) + t;
}
// assign the variables
days = convertTime(days);
hours = convertTime(hours);
minutes = convertTime(minutes);
seconds = convertTime(seconds);
// Make sure the "00:" is present if empty.
if(days !== "00"){
var currentTimeString = days + ":" + hours + ":" + minutes + ":" + seconds;
return currentTimeString;
} else if (hours !== "00"){
var currentTimeString = hours + ":" + minutes + ":" + seconds;
return currentTimeString
} else if(minutes !== "0:00"){
var currentTimeString = minutes + ":" + seconds;
return currentTimeString
} else {
var currentTimeString = seconds;
return currentTimeString
}
}
Any help is welcome.
Thanks in advance.
Greets,
Michel
resetTimer needs to set flag to 0. If it leaves it set at 1, then toggleTimer will call pauseTimer rather than startTimer.
BTW, it's better style to use boolean values (true/false) for flags.
Just remove clearInterval(timerTime); in function resetTimer();
function resetTimer() {
//clearInterval(timerTime);
document.getElementById('showTime').innerHTML = (calculateTime(300));
document.getElementById("btnUp").disabled = false;
document.getElementById("btnDwn").disabled = false;
return time = 300;
}

Countdown HH:MM:SS in Jquery

I want to countdown timer in format of hh:mm:ss so I use this code it's convert seconds into required format but when I count down it display me NaN. Can you tell me what I am doing wrong
Here is code
<div id="timer"></div>
JS
String.prototype.toHHMMSS = function () {
var sec_num = parseInt(this, 10); // don't forget the second parm
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
var time = hours + ':' + minutes + ':' + seconds;
return time;
}
var count = '62';
count = count.toHHMMSS();
var counter = setInterval(timer, 1000);
function timer() {
count--;
if (count <= 0) {
clearInterval(counter);
return;
}
$('#timer').html(count);
}
Here is JsFiddle link CountDown Timer
Well, let's take a look at what your code does:
Set count to the string value 62.
Convert it to HHMMSS, so now count is equal to the string 00:01:02
Start the timer.
On the first run of the timer, decrement count. Erm... count is a string, you can't decrement it. The result is not a number.
Okay, so with that out of the, way how about fixing it:
function formatTime(seconds) {
var h = Math.floor(seconds / 3600),
m = Math.floor(seconds / 60) % 60,
s = seconds % 60;
if (h < 10) h = "0" + h;
if (m < 10) m = "0" + m;
if (s < 10) s = "0" + s;
return h + ":" + m + ":" + s;
}
var count = 62;
var counter = setInterval(timer, 1000);
function timer() {
count--;
if (count < 0) return clearInterval(counter);
document.getElementById('timer').innerHTML = formatTime(count);
}
var count = '62'; // it's 00:01:02
var counter = setInterval(timer, 1000);
function timer() {
if (parseInt(count) <= 0) {
clearInterval(counter);
return;
}
var temp = count.toHHMMSS();
count = (parseInt(count) - 1).toString();
$('#timer').html(temp);
}
http://jsfiddle.net/5LWgN/17/
If you use the jquery moment plugin. If you are not using jQuery moment then you can use formatTime(seconds) function that is in the #Niet's answer https://stackoverflow.com/a/18506677/3184195
var start_time = 0;
var start_timer = null;
start_timer = setInterval(function() {
start_time++;
var formate_time = moment.utc(start_time * 1000).format('mm:ss');
$('#Duration').text(formate_time);
}, 1000);
});
function clear() {
if (start_timer) clearInterval(start_timer);
}

Categories

Resources