How to make "Start" button visible after clicking "Reset" button - javascript

I'm making a timer with jQuery. When you press the "Reset" button, it is supposed to make the "Start" button visible again.
I am getting this error:
Clicking the "Reset" button:
The selector "#reset" does not render the expected css for property "display": expected 'inline-block' to deeply equal 'none'
Here is my html:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Interactivity</title>
<meta charset="utf-8"/>
<link rel="stylesheet" type="text/css" href="styles/site.css"/>
<script src="scripts/jquery-3.2.1.min.js"></script>
<script src="scripts/formatTime.js"></script>
<script src="scripts/times.js"></script>
<script src="scripts/reset.js"></script>
</head>
<body>
<div id="text">
<p>
Can you internally count 45 seconds precisely?
</p>
</div>
<button id="start">Start Timer</button>
<button id="stop" style="display: none;">Stop Timer</button>
<button id="reset" style="display: none;">Reset Timer</button>
<span id="time_started" class="hidden" style="display: none;">Timer Started</span>
<span id="time_ended" class="hidden">Timer Ended</span>
</body>
</html>
Here is my css:
body {
background-color: white;
font-family: sans-serif;
margin: 200px auto 0;
max-width: 900px;
}
h1 {
text-align: center;
}
div {
margin-bottom: 50px;
}
.hidden {
display: none;
}
Here is reset.js:
// reset everything
$("#reset").on('click',function() {
$(".results").addClass("hidden");
$("#reset").addClass("hidden");
$("#start").removeClass("hidden");
$("#time_started").addClass("hidden");
$("#time_ended").addClass("hidden");
});
Here is formatTime.js:
// formats the current date/time so that it reads as hh:mm:ss PM/AM
function formatTime(time) {
var
end_time,
formatted_time,
formatted_end_time,
start_time,
hour = 12,
minute = 10,
second = 10,
meridies;
hour = time.getHours();
if (hour>12) {
hour = hour-12;
meridies = "PM";
} else {
meridies = "AM";
}
minute = time.getMinutes();
if (minute<10) {
minute = "0"+minute;
}
second = time.getSeconds();
if (second<10) {
second = "0"+second;
}
return hour+":"+minute+":"+second+" "+meridies;
}
Here is times.js:
/* global formatTime: true */
/* Please do not remove the comment above. */
// timer to calculate the starting and stopping clicks
var start_time;
var formatted_time;
var end_time;
var formatted_end_time;
var time_change;
$(document).ready(function() {
$("#start").on('click',function() {
$("#start").hide();
$("#stop").show();
$("#time_started").hide();
$("#time_ended").hide();
end_time = new Date();
start_time = new Date();
formatted_time = formatTime(start_time);
});
$("#stop").on('click',function() {
$("#stop").hide();
$("#reset").show();
$("#time_started").hide();
$("#time_ended").show();
end_time = new Date();
formatted_end_time = formatTime(end_time);
$("body").append("<p class='results'>You started at "+formatted_time+".</p>");
$("body").append("<p class='results'>You finished at "+formatted_end_time+".</p>");
time_change = end_time-start_time;
$("body").append("<p class='results'>You counted "+(time_change/1000)+" seconds.</p>");
$("body").append("<p class='results'>You are off by "+(time_change/1000-45)+" seconds.</p>");
});
});

Avoid mixing addClass() / removeClass() vs hide() / show().
It should be obvious what addClass() / removeClass() do. hide() / show() add and remove inline css styles to achieve a similar end result (but inline styles will always take precedence).
$(function() {
$("#reset").on("click", function() {
$(".results").remove();
$("#reset").addClass("hidden");
$("#time_ended").addClass("hidden");
$("#start").removeClass("hidden");
});
// timer to calculate the starting and stopping clicks
var start_time;
var formatted_time;
var end_time;
var formatted_end_time;
var time_change;
$("#start").on("click", function() {
$("#start").addClass("hidden");
$("#stop").removeClass("hidden");
$("#time_started").removeClass("hidden");
$("#time_ended").addClass("hidden");
end_time = new Date();
start_time = new Date();
formatted_time = formatTime(start_time);
});
$("#stop").on("click", function() {
// $("#stop").hide();
$("#stop").addClass("hidden");
// $("#reset").show();
$("#reset").removeClass("hidden");
// $("#time_started").hide();
$("#time_started").addClass("hidden");
// $("#time_ended").show();
$("#time_ended").removeClass("hidden");
end_time = new Date();
formatted_end_time = formatTime(end_time);
$("body").append(
"<p class='results'>You started at " + formatted_time + ".</p>"
);
$("body").append(
"<p class='results'>You finished at " + formatted_end_time + ".</p>"
);
time_change = end_time - start_time;
$("body").append(
"<p class='results'>You counted " + time_change / 1000 + " seconds.</p>"
);
$("body").append(
"<p class='results'>You are off by " +
(time_change / 1000 - 45) +
" seconds.</p>"
);
});
});
function formatTime(time) {
var end_time,
formatted_time,
formatted_end_time,
start_time,
hour = 12,
minute = 10,
second = 10,
meridies;
hour = time.getHours();
if (hour > 12) {
hour = hour - 12;
meridies = "PM";
} else {
meridies = "AM";
}
minute = time.getMinutes();
if (minute < 10) {
minute = "0" + minute;
}
second = time.getSeconds();
if (second < 10) {
second = "0" + second;
}
return hour + ":" + minute + ":" + second + " " + meridies;
}
.hidden {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="text">
<p>
Can you internally count 45 seconds precisely?
</p>
</div>
<button id="start">Start Timer</button>
<button id="stop" class="hidden">Stop Timer</button>
<button id="reset" class="hidden">Reset Timer</button>
<span id="time_started" class="hidden">Timer Started</span>
<span id="time_ended" class="hidden">Timer Ended</span>
Also, be careful when appending new content on every round and then just hiding it at the end (instead of actually removing it). You would end up with unnecessarily duplicated html.
Alternatively you could add the .results in the starting html with a class of .hidden to use the same hide/show method for everything.
$(function() {
$("#reset").on("click", function() {
$(".results").addClass("hidden");
$("#reset").addClass("hidden");
$("#time_ended").addClass("hidden");
$("#start").removeClass("hidden");
});
// timer to calculate the starting and stopping clicks
var start_time;
var formatted_time;
var end_time;
var formatted_end_time;
var time_change;
$("#start").on("click", function() {
$("#start").addClass("hidden");
$("#stop").removeClass("hidden");
$("#time_started").removeClass("hidden");
$("#time_ended").addClass("hidden");
end_time = new Date();
start_time = new Date();
formatted_time = formatTime(start_time);
});
$("#stop").on("click", function() {
$("#stop").addClass("hidden");
$("#reset").removeClass("hidden");
$("#time_started").addClass("hidden");
$("#time_ended").removeClass("hidden");
$(".results").removeClass("hidden");
end_time = new Date();
formatted_end_time = formatTime(end_time);
time_change = end_time - start_time;
$('#results-time-started span').text(formatted_time);
$('#results-time-ended span').text(formatted_end_time);
$('#results-time-counted span').text(time_change / 1000);
$('#results-time-off-by span').text(time_change / 1000 - 45);
});
});
function formatTime(time) {
var end_time,
formatted_time,
formatted_end_time,
start_time,
hour = 12,
minute = 10,
second = 10,
meridies;
hour = time.getHours();
if (hour > 12) {
hour = hour - 12;
meridies = "PM";
} else {
meridies = "AM";
}
minute = time.getMinutes();
if (minute < 10) {
minute = "0" + minute;
}
second = time.getSeconds();
if (second < 10) {
second = "0" + second;
}
return hour + ":" + minute + ":" + second + " " + meridies;
}
.hidden {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="text">
<p>
Can you internally count 45 seconds precisely?
</p>
</div>
<button id="start">Start Timer</button>
<button id="stop" class="hidden">Stop Timer</button>
<button id="reset" class="hidden">Reset Timer</button>
<span id="time_started" class="hidden">Timer Started</span>
<span id="time_ended" class="hidden">Timer Ended</span>
<p id='results-time-started' class='hidden results'>You started at <span></span>.</p>
<p id='results-time-ended' class='hidden results'>You finised at <span></span>.</p>
<p id='results-time-counted' class='hidden results'>You counted <span></span> seconds.</p>
<p id='results-time-off-by' class='hidden results'>You are off by <span></span> seconds.</p>

Related

12 hour clock not displaying, but 24 hour clock displaying fine

I have this code so that when I click the buttons, it switches between the 12 hours clock and 24 hours clock.
The 24 hour clock displayed, but when I click the 12 hour clock button, nothing happens.
Google Inspect also says nothing. Any help would be appreciated.
function twelvehour() {
var dat = new Date();
var h = dat.getHours()
if (h >= 13) {
var h = dat.getHours() - 12
} else {
var h = dat.getHours()
}
var m = dat.getMinutes()
var s = dat.getSeconds()
if (h >= 12) {
document.getElementById("clock").innerHTML = h + ":" + m + ":" + s + "pm"
} else {
document.getElementById("clock").innerHTML = h + ":" + m + ":" + s
}
}
function tfourhour() {
var dat1 = new Date();
var h1 = dat1.getHours()
var m1 = dat1.getMinutes()
var s1 = dat1.getSeconds()
document.getElementById("clock").innerHTML = h1 + ":" + m1 + ":" + s1
}
setInterval(twelvehour, 1000);
setInterval(tfourhour, 1000);
document.getElementById("twelve").onclick = twelvehour()
document.getElementById("tfour").onclick = tfourhour()
<html>
<head>
<style>
button {
display: inline-block;
}
</style>
<title>Assignment 9c Clock</title>
</head>
<body>
<button type="button" style="width=500, height=500" id="twelve">12 Hour Clock</button>
<button type="button" style="width=500, height=500" id="tfour">24 Hour Clock</button>
<br>
<p id="clock"></p>
<script type="text/javascript" src="sample4.js">
</script>
</body>
</html>
You run two functions at the same time by calling setIterval twice.
twelvehour function doesn't work properly since you set h before it displayed.
Event handlers should be mapped with a function itself not a result of it.
And consider using a function that store the selected function.
let f = twelvehour;
f();
function twelvehour() {
var dat = new Date();
dat.setHours(14); // for test
var h = dat.getHours()
var m = dat.getMinutes()
var s = dat.getSeconds()
if (h >= 12) {
document.getElementById("clock").innerHTML = (h - 12) + ":" + m + ":" + s + "pm"
} else {
document.getElementById("clock").innerHTML = h + ":" + m + ":" + s
}
}
function tfourhour() {
var dat1 = new Date();
dat1.setHours(14); // for test
var h1 = dat1.getHours()
var m1 = dat1.getMinutes()
var s1 = dat1.getSeconds()
document.getElementById("clock").innerHTML = h1 + ":" + m1 + ":" + s1
}
setInterval(() => f(), 1000);
document.getElementById("twelve").onclick = () => { f = twelvehour; f(); }
document.getElementById("tfour").onclick = () => { f = tfourhour; f(); }
<html>
<head>
<style>
button {
display: inline-block;
}
</style>
<title>Assignment 9c Clock</title>
</head>
<body>
<button type="button" style="width=500, height=500" id="twelve">12 Hour Clock</button>
<button type="button" style="width=500, height=500" id="tfour">24 Hour Clock</button>
<br>
<p id="clock"></p>
</script>
</body>
</html>
Your main issue here is assigning onclick in a wrong way. You should drop the parentheses:
document.getElementById("twelve").onclick = twelvehour
Or, put it in the HTML:
<button type="button"
style="width: 500px; height: 500px;"
id="twelve"
onclick="twelvehour()">12 Hour Clock</button>
Here's how I would do it:
function Clock(displayFunc, twelveHour = true, interval = 1000){
let clock;
this.twelveHour = twelveHour; this.interval = interval;
this.start = ()=>{
const fun = ()=>{
let d = new Date, h = d.getHours(), m = d.getMinutes(), s = d.getSeconds(), z = d.getMilliseconds(), p = false;
if(this.twelveHour){
if(h > 12){
h -= 12; p = 'pm';
}
else{
p = 'am';
}
}
else if(h < 10){
h = '0'+h;
}
if(m < 10)m = '0'+m;
if(s < 10)s = '0'+s;
if(z < 10){
z = '00'+z;
}
else if(z < 99){
z = '0'+z;
}
displayFunc({hours:h.toString(), minutes:m.toString(), seconds:s.toString(), am_pm:p});
}
fun(); clock = setInterval(fun, this.interval);
return this;
}
this.stop = ()=>{
clearInterval(clock); clock = undefined;
return this;
}
}
let doc, bod, I; // for use on other loads
addEventListener('load', ()=>{
doc = document; bod = doc.body; I = id=>doc.getElementById(id);
const digital = I('digital'), clock = new Clock(o=>{
digital.textContent = o.hours+':'+o.minutes+':'+o.seconds+' '+o.am_pm;
});
clock.start();
}); // end load
<div id='digital'></div>

multiple stopwatch not working correctly

I have made two stopwatch to track activity of a user, one gets paused when another starts/resumes. But its getting the time from other clock everytime. please help me with correction, or please suggest any better way of doing this, I want to use 10 stopwatch together to keep track on activity and want my all stopwatches in one side and buttons on another. Thanks in advance.
$(document).ready(function(){
var clocDiv = '';
$(".act-butn").button().click(function(){
var act = $(this).attr('value');
clocDiv = '#'+act+' span';
prev_hours = parseInt($(clocDiv).eq(0).html());
prev_minutes = parseInt($(clocDiv).eq(1).html());
prev_seconds = parseInt($(clocDiv).eq(2).html());
prev_milliseconds = parseInt($(clocDiv).eq(3).html());
updateTime(prev_hours, prev_minutes, prev_seconds, prev_milliseconds);
});
// Update time in stopwatch periodically - every 25ms
function updateTime(prev_hours, prev_minutes, prev_seconds, prev_milliseconds){
var startTime = new Date(); // fetch current time
timeUpdate = setInterval(function () {
var timeElapsed = new Date().getTime() - startTime.getTime(); // calculate the time elapsed in milliseconds
// calculate hours
hours = parseInt(timeElapsed / 1000 / 60 / 60) + prev_hours;
// calculate minutes
minutes = parseInt(timeElapsed / 1000 / 60) + prev_minutes;
if (minutes > 60) minutes %= 60;
// calculate seconds
seconds = parseInt(timeElapsed / 1000) + prev_seconds;
if (seconds > 60) seconds %= 60;
// calculate milliseconds
milliseconds = timeElapsed + prev_milliseconds;
if (milliseconds > 1000) milliseconds %= 1000;
// set the stopwatch
setStopwatch(hours, minutes, seconds, milliseconds);
}, 25); // update time in stopwatch after every 25ms
}
// Set the time in stopwatch
function setStopwatch(hours, minutes, seconds, milliseconds){
$(clocDiv).eq(0).html(prependZero(hours, 2));
$(clocDiv).eq(1).html(prependZero(minutes, 2));
$(clocDiv).eq(2).html(prependZero(seconds, 2));
$(clocDiv).eq(3).html(prependZero(milliseconds, 3));
}
// Prepend zeros to the digits in stopwatch
function prependZero(time, length) {
time = new String(time); // stringify time
return new Array(Math.max(length - time.length + 1, 0)).join("0") + time;
}
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>
<div id="break">
<span id="hours">00</span> :
<span id="minutes">00</span> :
<span id="seconds">00</span> ::
<span id="milliseconds">000</span>
</div><br>
<div id="production">
<span id="hours">00</span> :
<span id="minutes">00</span> :
<span id="seconds">00</span> ::
<span id="milliseconds">000</span>
</div><br>
<div id="controls">
<button class="act-butn" value="break">Break</button>
<button class="act-butn" value="production">Production</button>
</div>
for your code, 'id' are unique, you should not use same id more than once.
what I did here have two part,
1st part are stop watch, you can create as many stop watch you want. just copy more <span class="basic stopwatch">Watch x</span> but make sure you have same number of btngroup and watchgroup
2nd part below will drive all clock dynamically, start one will pause all others:
//click one btn, stop all other watch
$('#btngroup button').live('click', function() {
var btnClicked = $(this).index();
$('.basic').each(function(index) {
if(btnClicked == index){
$(this).find('a:eq(0)')[0].click();
} else {
$(this).find('a:eq(1)')[0].click();
}
});
});
lots of code, play around and should fit your need
// stopwatch functions...
var Stopwatch = function(elem, options) {
var timer = createTimer(),
startButton = createButton("start", start),
stopButton = createButton("stop", stop),
resetButton = createButton("reset", reset),
offset,
clock,
interval;
// default options
options = options || {};
options.delay = options.delay || 1;
// append elements
elem.appendChild(timer);
elem.appendChild(startButton);
elem.appendChild(stopButton);
elem.appendChild(resetButton);
// initialize
reset();
// private functions
function createTimer() {
return document.createElement("span");
}
function createButton(action, handler) {
var a = document.createElement("a");
a.href = "#" + action;
a.style = "display: none;";
a.innerHTML = action;
a.addEventListener("click", function(event) {
handler();
event.preventDefault();
});
return a;
}
function start() {
if (!interval) {
offset = Date.now();
interval = setInterval(update, options.delay);
}
}
function stop() {
if (interval) {
clearInterval(interval);
interval = null;
}
}
function reset() {
clock = 0;
render(0);
}
function update() {
clock += delta();
render();
}
function render() {
var h = Math.floor(clock / (1000 * 60 * 60)) % 24;
var m = Math.floor(clock / (1000 * 60)) % 60;
var s = Math.floor(clock / 1000) % 60;
var ms = Math.floor(clock % 1000);
if (h < 10) {
h = "0" + h;
}
if (m < 10) {
m = "0" + m;
}
if (s < 10) {
s = "0" + s;
}
if (ms < 100) {
ms = "0" + ms;
}
if (ms < 10) {
ms = "0" + ms;
}
timer.innerHTML = h + ':' + m + ':' + s + '::' + ms;
}
function delta() {
var now = Date.now(),
d = now - offset;
offset = now;
return d;
}
this.start = start;
this.stop = stop;
this.reset = reset;
};
var elems = document.getElementsByClassName("basic");
for (var i = 0, len = elems.length; i < len; i++) {
new Stopwatch(elems[i]);
}
//click one btn, stop all other watch
$('#btngroup button').live('click', function() {
var btnClicked = $(this).index();
$('.basic').each(function(index) {
if(btnClicked == index){
$(this).find('a:eq(0)')[0].click();
} else {
$(this).find('a:eq(1)')[0].click();
}
});
});
.stopwatch {
display: inline-block;
background-color: white;
border: 1px solid #eee;
padding: 5px;
margin: 5px;
}
.stopwatch span {
font-weight: bold;
display: block;
}
.stopwatch a {
padding-right: 5px;
text-decoration: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="btngroup">
<button>Btn 1</button>
<button>Btn 2</button>
<button>Btn 3</button>
<button>Btn 4</button>
<button>Btn 5</button>
<button>Btn 6</button>
<button>Btn 7</button>
<button>Btn 8</button>
<button>Btn 9</button>
<button>Btn 10</button>
</div>
<br><br>
<div id="watchgroup">
<span class="basic stopwatch">Watch 1</span>
<span class="basic stopwatch">Watch 2</span>
<span class="basic stopwatch">Watch 3</span>
<span class="basic stopwatch">Watch 4</span>
<span class="basic stopwatch">Watch 5</span>
<span class="basic stopwatch">Watch 6</span>
<span class="basic stopwatch">Watch 7</span>
<span class="basic stopwatch">Watch 8</span>
<span class="basic stopwatch">Watch 9</span>
<span class="basic stopwatch">Watch 10</span>
</div>

How to check how long you hover an element in pure javascript?

I want to show a tootip when an element is hovered for 2 seconds or more. How can I do it?
var startTime, endTime;
function handlerIn() {
startTime = new Date();
}
function handlerOut() {
endTime = new Date();
var timeDiff = endTime - startTime; //in ms
// strip the ms
timeDiff /= 1000;
// get seconds
var seconds = Math.round(timeDiff % 60);
console.log("hover during " + seconds + " sec");
}
.hover {
background-color: red;
width: 100px;
height: 100px;
}
<div class="hover" onmouseenter="handlerIn()" onmouseleave="handlerOut()">HOVER ME</div>
<div id="seconds"></div>
You can check the enter time and exit time with onmouseenter="fn()" and onmouseout="fn()". Here's a simple way to do it and it also displays the time in miliseconds!
var time = 0;
var hover = 0;
var out = 0;
function getInTime() {
hover = Date.now();
}
function getOutTime() {
out = Date.now();
time = out-hover;
document.getElementById('time').innerHTML = " Show hover time: " + time + 'ms';
}
<button onmouseout="getOutTime()" onmouseenter="getInTime()" >Hover Here</button>
<br /><br />
<button id="time">Hover Time</button>
You can use setTimeout() method with onmouseover and onmouseout events.
Tooltip css:
http://www.w3schools.com/howto/howto_css_tooltip.asp
setTimeout method: http://www.w3schools.com/jsref/met_win_settimeout.asp
<div id="example" class="tooltip" onmouseover="start()" onmouseout="stop()">example text</div>
let t, hoverTime=2000;
function start(){
t = setTimeout('showTooltip()', hoverTime);
}
function showTooltip(){
let node = document.createElement("span");
let textnode = document.createTextNode("Tooltip text");
node.className='tooltiptext';
node.appendChild(textnode);
document.getElementById("example").appendChild(node);
}
function stop(){
clearTimeout(t);
if(document.getElementById("example").childNodes[1]){
document.getElementById("example").removeChild(document.getElementById("example").childNodes[1]);
}
}

How do I display millisecond in my stopwatch?

I am implementing a stopwatch by using Javascript. I have basic html document setup and a javascript file called stopwatch.js in which I have the following code. I make use of setInterval function to execute the clockRunning function every 1 second(1000ms). This gives me control over sec, min and hour to increment them accordingly, but I am having difficulty with inserting millisecond into the stopwatch. How should I increment the millisecond from 0 to 1000 and then reset to zero?
I have tried by decreasing the interval time for setInterval function to be called every 1ms and then set millisecond variable to time%1000 in which time variable is increased by 1 every time the function is called. But it does not give the result I want. The millisecond seems to be increasing way too slow.
var running = 0
var time = 0;
var hour = 0;
var min = 0;
var sec = 0;
var millisec = 0;
function start(){
started = window.setInterval(clockRunning, 1000);
}
function stop(){
window.clearInterval(started);
}
function clockRunning(){
time++;
sec++;
if (sec == 60){
min += 1;
sec = 0;
if (min == 60){
hour += 1;
min = 0;
}
}
document.getElementById("display-area").innerHTML = (hour ? (hour > 9 ? hour : "0" + hour) : "00")
+ ":" + (min ? (min > 9 ? min : "0" + min) : "00") + ":" + (sec > 9 ? sec : "0"
+ sec);
};
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Stopwatch</title>
<script src="stopwatch.js"></script>
<style>
#display-area { font-size: 20pt; }
</style>
</head>
<body>
<div>
<output id="display-area">00:00:00.000</output>
</div>
<div>
<button id="toggle-button" onClick="start()">Start</button>
<button id="toggle-button" onClick="stop()">Stop</button>
<button id="reset-button">Reset</button>
</div>
</body>
</html>
You should keep track of the starting time then subtract that time from the current time using a Date:
var timeBegan = null
, timeStopped = null
, stoppedDuration = 0
, started = null;
function start() {
if (timeBegan === null) {
timeBegan = new Date();
}
if (timeStopped !== null) {
stoppedDuration += (new Date() - timeStopped);
}
console.log(stoppedDuration);
started = setInterval(clockRunning, 10);
}
function stop() {
timeStopped = new Date();
clearInterval(started);
}
function reset() {
clearInterval(started);
stoppedDuration = 0;
timeBegan = null;
timeStopped = null;
document.getElementById("display-area").innerHTML = "00:00:00.000";
}
function clockRunning(){
var currentTime = new Date()
, timeElapsed = new Date(currentTime - timeBegan - stoppedDuration)
, hour = timeElapsed.getUTCHours()
, min = timeElapsed.getUTCMinutes()
, sec = timeElapsed.getUTCSeconds()
, ms = timeElapsed.getUTCMilliseconds();
document.getElementById("display-area").innerHTML =
(hour > 9 ? hour : "0" + hour) + ":" +
(min > 9 ? min : "0" + min) + ":" +
(sec > 9 ? sec : "0" + sec) + "." +
(ms > 99 ? ms : ms > 9 ? "0" + ms : "00" + ms);
};
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Stopwatch</title>
<style>
#display-area { font-size: 20pt; }
</style>
</head>
<body>
<div>
<output id="display-area">00:00:00.000</output>
</div>
<div>
<button id="toggle-button" onClick="start()">Start</button>
<button id="toggle-button" onClick="stop()">Stop</button>
<button id="reset-button" onClick="reset()">Reset</button>
</div>
</body>
</html>
The reason you were seeing the milliseconds "lagging" before was that setInterval is notorious for not firing exactly when you specify. You can get around this using the strategy above.
Update: You could keep track of how long the timer has "paused" between resets. Updated my answer to accommodate this.
complete code here
$(document).ready(function () {
var milliseconds;
var hours;
var minutes;
var seconds;
var interval;
var count = 0;
var lap;
var i = 0;
$(".heading").slideDown("slow"); //slide down heading countdown.
// click function to start timer
$(".start").click(function () {
$(".start").hide();
$(".pause").show(100); // show pause button
$("#end").text("Stopwatch Started"); // change text.
interval = setInterval(newtimer, 10); // run the countdown interval of 1000 millisecond
});
function newtimer() {
hours = parseInt(count * 10 / 1000 / 60 / 60);// calculate hours
minutes = parseInt(count * 10 / 1000 / 60); // calculate minutes
seconds = parseInt((count * 10 / 1000)%60);// calculate seconds
milliseconds = parseInt((count*10) % 1000); // calculate milliseconds
/* display digits in clock manner */
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
count++; // increment in count.
$(".seconds").text(hours + " : " + minutes + " : " + seconds + " : " + milliseconds);
}
/* click function to pause timer*/
$(".pause").click(function () {
$(".start").hide(); //hide start button
$(".restart").hide(); //hide restart button
$(".pause").hide();
$(".resume").show(); // show resume button.
$("#end").text("Stopwatch Paused");
clearInterval(interval); //clear interval will stop the count.
i = i + 1;
lap = " " + hours + " : " + minutes + " : " + seconds + " : " + milliseconds;
$(".lap").append('<p>' + 'Time Lap' + "-" + i + lap + '</p>'); // add p tag in div and count no. of laps.
});
/* click function to resume the countdown */
$(".resume").click(function () {
$("#end").text("Stopwatch Resumed");// change end text.
$(".pause").show();
$(".resume").hide();
interval = setInterval(newtimer, 10);// interval to function new timer. count will remain same where paused.
});
/* click function to stop stopwatch */
$(".stop").click(function () {
$("#end").text("Stopwatch Stopped");
$(".restart").show(); //show restart button
$(".resume").hide(); // hide resume button
$(".start").hide();// hide start button
$(".pause").hide();
$(".lap p").remove(); // remove laps.
clearInterval(interval);
});
/*click function to restart stopwatch*/
$(".restart").click(function () {
$("#end").text("Stopwatch Restarted");// change end text.
$(".restart").hide();
$(".pause").show();
count = 0; // count reset to zero
interval = setInterval(newtimer, 10); //time interval to function new timer
});
/* click function on class reset to reset the countdown */
$(".reset").click(function () {
$(".seconds").text("00 : 00 : 00 : 00"); // set display to initial value.
$(".resume").hide(); // hide resume button
$(".start").show(); // show start button
$(".pause").hide(); // hide pause button
$(".restart").hide(); // hide restart button
$("#end").text(" "); // change end text
$(".lap p").remove(); // remove p tag from div
clearInterval(interval); // clear interval
count = 0; // reset count to initial value.
});
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>stopwatch</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script></head>
<body style="font-family: cursive;">
<div class="container-fluid clearfix" style="padding:100px; background-color:lightgrey;">
<div style="width:25%; float:left"><img src="./bn.jpg" alt="stopwatch" style="width:100%"></div>
<div class="heading" style="color:#165caa;display:none;margin-left: 365px;font-size: 84px">STOPWATCH</div>
<div class="seconds" style="font-size: 46px;text-align:center;margin-top:30px "> 00 : 00 : 00 : 00</div>
<div style="text-align:center;">
<button class="start mt-3 px-4 btn btn-success">START</button>
<button class="restart mt-3 px-4 btn btn-success" style="display:none">RESTART</button>
<button class="resume mt-3 px-4 btn btn-success" style="display:none">RESUME</button>
<button class="pause mt-3 px-4 btn btn-warning" style="display: none">PAUSE</button>
<button class="stop mt-3 px-4 btn btn-dark">STOP</button>
<button class="reset mt-3 px-4 btn btn-danger">RESET</button>
</div>
<p id="end" style="font-size:32px ;margin-top:30px;text-align:center"></p>
<div class="lap" style="text-align: center; font-size:16px;font-family: monospace;"></div>
</div>
</body>
</html>
BUG FIX!!!
I noticed the Start, Stop, Reset would not work if you hit Start more than once with the code above. I was able to fix this by tweaking the start function!
function start() {
if (timeBegan === null) {
timeBegan = new Date();
}else {
clearInterval(started);
};
if (timeStopped !== null) {
stoppedDuration += (new Date() - timeStopped);
};
if (stoppedDuration < 1000){
console.log(stoppedDuration+' ms');
};
if (stoppedDuration > 1000){
console.log(stoppedDuration/1000+' seconds');
};
started = setInterval(clockRunning, 10);
return stoppedDuration }

Having trouble with Javascript Stopwatch

I'm working on a stopwatch, and this is my code for it. It makes perfect sense for me, but doesn't want to update for some reason.
HTML:
<ul>
<li id="hour">0</li>
<li>:</li>
<li id="min">0</li>
<li>:</li>
<li id="sec">0</li>
</ul>
JS:
var sec = document.getElementById("sec").value,
min = document.getElementById("min").value,
hour = document.getElementById("hour").value;
function stopWatch(){
sec++;
if(sec > 59) {
sec = 0;
min++;
} else if(min > 59){
min = 0;
hour++;
}
window.setTimeout("stopWatch()", 1000);
}
stopWatch();
A list item has no .value property. Inputs or textareas have. It should be
var sec = parseInt(document.getElementById("sec").innerHTML, 10),
min = parseInt(document.getElementById("min").innerHTML, 10),
hour = parseInt(document.getElementById("hour").innerHTML, 10);
which is also parsing them into numbers.
Also, don't pass a string to setTimeout. Pass the function you want to be called:
window.setTimeout(stopWatch, 1000);
And nowhere in your code you are outputting the updated variables. They are no magic pointers to the DOM properties, but just hold numbers (or strings in your original script).
Last but not least there's a logic error in your code. You are checking whether the minutes exceed 59 only when the seconds didn't. Remove that else before the if.
1) List items LI don't have values, they have innerHTML.
var sec = document.getElementById("sec").innerHTML; (not .value)
2) Nowhere in your code do you set the contents of your LIs. JavaScript doesn't magically associate IDs with variables - you have to do that bit yourself.
Such as:
document.getElementById("hour").innerHTML = hour;
3) Never pass a timeout as a string. Use an anonymous function:
window.setTimeout(function() {stopWatch()}, 1000);
or, plainly:
window.setTimeout(stopWatch, 1000);
(function() {
var sec = document.getElementById("sec").value,
min = document.getElementById("min").value,
hour = document.getElementById("hour").value;
function stopWatch(){
sec++;
if(sec > 59) {
sec = 0;
min++;
} else if(min > 59){
min = 0;
hour++;
}
document.getElementById("sec").textContent = sec
document.getElementById("min").textContent = min
document.getElementById("hour").textContent = hour
window.setTimeout(stopWatch, 1000);
}
stopWatch();
})();
The invocation should only be
window.setInterval(stopWatch, 1000);
So to use the stopwatch, put the function inside:
var sec = 0, min = 0, hour = 0;
window.setInterval(function () {
"use strict";
sec++;
if (sec > 59) {
sec = 0;
min++;
} else if (min > 59) {
min = 0;
hour++;
}
document.getElementById("sec").innerHTML = sec;
document.getElementById("min").innerHTML = hour;
document.getElementById("hour").innerHTML = hour;
}, 1000);
Li elements has no value propertie, use innerHTML.
You could store the values for sec, min & hour in variables.
It is a nice idea to store the setTimeout() call to a variable in case you want to stop the clock later. Like "pause".
http://jsfiddle.net/chepe263/A3a9m/4/
<html>
<head>
<style type="text/css">
ul li{
float: left;
list-style-type: none !important;
}
</style>
<script type="text/javascript">//<![CDATA[
window.onload=function(){
var sec = min = hour = 0;
var clock = 0;
stopWatch = function(){
clearTimeout(clock);
sec++;
if (sec >=59){
sec = 0;
min++;
}
if (min>=59){
min=0;
hour++;
}
document.getElementById("sec").innerHTML = (sec < 10) ? "0" + sec : sec;
document.getElementById("min").innerHTML = (min < 10) ? "0" + min : min;
document.getElementById("hour").innerHTML = (hour < 10) ? "0" + hour : hour;
clock = setTimeout("stopWatch()",1000); }
stopWatch();
pause = function(){
clearTimeout(clock);
return false;
}
play = function(){
stopWatch();
return false;
}
reset = function(){
sec = min = hour = 0;
stopWatch();
return false;
}
}//]]>
</script>
</head>
<body>
<ul>
<li id="hour">00</li>
<li>:</li>
<li id="min">00</li>
<li>:</li>
<li id="sec">49</li>
</ul>
<hr />
Pause
Continue
Reset
</body>
</html>
This is my complete code, this may help you out:
<html>
<head>
<title>Stopwatch Application ( Using JAVASCRIPT + HTML + CSS )</title>
<script language="JavaScript" type="text/javascript">
var theResult = "";
window.onload=function() { document.getElementById('morefeature').style.display = 'none'; }
function stopwatch(text) {
var d = new Date(); var h = d.getHours(); var m = d.getMinutes(); var s = d.getSeconds(); var ms = d.getMilliseconds();
document.stopwatchclock.stpwtch.value = + h + " : " + m + " : " + s + " : " + ms;
if (text == "Start") {
document.stopwatchclock.theButton.value = "Stop";
document.stopwatchclock.theButton.title = "The 'STOP' button will save the current stopwatch time in the stopwatch history, halt the stopwatch, and export the history as JSON object. A stopped stpwatch cannot be started again.";
document.getElementById('morefeature').style.display = 'block';
}
if (text == "Stop") {
var jsnResult = arrAdd();
var cnt = 0; var op= 'jeson output';
for (var i = 0; i < jsnResult.length; i++) {
if (arr[i] !== undefined) {
++cnt; /*json process*/
var j={ Record : cnt, Time : arr[i]};
var dq='"';
var json="{";
var last=Object.keys(j).length;
var count=0;
for(x in j){ json += dq+x+dq+":"+dq+j[x]+dq; count++;
if(count<last)json +=",";
}
json+="}<br>";
document.write(json);
}
}
}
if (document.stopwatchclock.theButton.value == "Start") { return true; }
SD=window.setTimeout("stopwatch();", 100);
theResult = document.stopwatchclock.stpwtch.value;
document.stopwatchclock.stpwtch.title = "Start with current time with the format (hours:mins:secs.milliseconds)" ;
}
function resetIt() {
if (document.stopwatchclock.theButton.value == "Stop") { document.stopwatchclock.theButton.value = "Start"; }
window.clearTimeout(SD);
}
function saveIt() {
var value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value; value++;
document.getElementById('number').value = value;
var resultTitle = '';
if(value == '1'){ resultTitle = "<h3>History</h3><hr color='black'>"; }
var objTo = document.getElementById('stopwatchresult')
var spanTag = document.createElement("span");
spanTag.id = "span"+value;
spanTag.className ="stopWatchClass";
spanTag.title ="The stopwatch showing current stopwatch time and a history of saved times. Each saved time are shown as total duration (split time - stopwatch start time) and a lap duration (split time - previous split time). And durations are shown in this format: 'hours:mins:secs.milliseconds'";
spanTag.innerHTML = resultTitle +"<br/><b>Record " + value+" =</b> " + theResult + "";
objTo.appendChild(spanTag);
arrAdd(theResult);
return;
}
var arr = Array();
function arrAdd(value){ arr.push(value); return arr;}
</script>
<style>
center {
width: 50%;
margin-left: 25%;
}
.mainblock {
background-color: #07c1cc;
}
.stopWatchClass {
background-color: #07c1cc;
display: block;
}
#stopwatchclock input {
margin-bottom: 10px;
width: 120px;
}
</style>
</head>
<body>
<center>
<div class="mainblock">
<h1><b title="Stopwatch Application ( Using JAVASCRIPT + HTML + CSS )">Stopwatch Application</b></h1>
<form name="stopwatchclock" id="stopwatchclock">
<input type="text" size="16" class="" name="stpwtch" value=" 00 : 00 : 00 : 00" title="Initially blank" />
<input type="button" name="theButton" id="start" onClick="stopwatch(this.value);" value="Start" title="The 'START' button is start the stopwatch. An already started stopwatch cannot be started again." /><br />
<div id="morefeature">
<input type="button" value="Reset" id="resetme" onClick="resetIt();reset();" title="Once you will click on 'RESET' button will entirely reset the stopwatch so that it can be started again." />
<input type="button" name="saver" id="split" value="SPLIT" onClick="saveIt();" title="The 'SPLIT' button will save the current stopwatch time in the stopwatch history. The stopwatch will continue to progress after split." />
<div>
<input type="hidden" name="number" id="number" value="0" />
</form>
</div>
<div id="stopwatchresult"></div>
</center>
</body>

Categories