start timer on two different html pages at the same time - javascript

I have pages page for timer control and other page for monitoring.
I want when I click on start timer, that the time start on control page and monitoring page at the same time and also stop together when stop is clicked
How can I do it?
var team1_timer = 00;
window.onload = function () {
var seconds = 00;
var tens = 00;
var appendTens = document.getElementById("tens")
var appendSeconds = document.getElementById("seconds")
var buttonStart = document.getElementById('button-start');
var buttonStop = document.getElementById('button-stop');
var buttonReset = document.getElementById('button-reset');
var Interval;
buttonStart.onclick = function() {
clearInterval(Interval);
Interval = setInterval(startTimer, 10);
}
buttonStop.onclick = function() {
clearInterval(Interval);
}
buttonReset.onclick = function() {
clearInterval(Interval);
tens = "00";
seconds = "00";
appendTens.innerHTML = tens;
appendSeconds.innerHTML = seconds;
}
function startTimer () {
tens++;
if(tens < 9){
appendTens.innerHTML = "0" + tens;
}
if (tens > 9){
appendTens.innerHTML = tens;
}
if (tens > 99) {
console.log("seconds");
seconds++;
team1_timer = seconds;
appendSeconds.innerHTML = "0" + seconds;
tens = 0;
appendTens.innerHTML = "0" + 0;
}
if (seconds > 9){
appendSeconds.innerHTML = seconds;
}
team1_timer = seconds;
}
///////////////////////////////////////////
var seconds_hold = 00;
var tens_hold = 00;
var appendTens_hold = document.getElementById("tens_hold")
var appendSeconds_hold = document.getElementById("seconds_hold")
var buttonStart_hold = document.getElementById('button-start_hold');
var buttonStop_hold = document.getElementById('button-stop_hold');
var buttonReset_hold = document.getElementById('button-reset_hold');
var Interval_hold ;
buttonStart_hold.onclick = function() {
clearInterval(Interval_hold);
Interval_hold = setInterval(startTimer_hold, 10);
}
buttonStop_hold.onclick = function() {
clearInterval(Interval_hold);
}
buttonReset_hold.onclick = function() {
clearInterval(Interval_hold);
tens_hold = "00";
seconds_hold = "00";
appendTens_hold.innerHTML = tens_hold;
appendSeconds_hold.innerHTML = seconds_hold;
}
function startTimer_hold () {
tens_hold++;
if(tens_hold < 9){
appendTens_hold.innerHTML = "0" + tens_hold;
}
if (tens_hold > 9){
appendTens_hold.innerHTML = tens_hold;
}
if (tens_hold > 99) {
console.log("seconds_hold");
seconds_hold++;
appendSeconds_hold.innerHTML = "0" + seconds_hold;
tens_hold = 0;
appendTens_hold.innerHTML = "0" + 0;
}
if (seconds_hold > 9){
appendSeconds_hold.innerHTML = seconds_hold;
}
}
}
<div class="wrapper" style="float:left;">
<a id="button-start" style="margin-right: 10px; margin-top: -12px;" class="btn btn-success">Start</a>
<button name="saveRoundTeam1" style=" margin-right: 10px;margin-top: -12px;" onclick="getTime()" class="btn btn-warning">Stop</button>
<a id="button-reset" class="btn btn-danger" style=" margin-right: 10px;margin-right:30px; margin-top: -12px;">Reset</a>
<span style="font-size:30px; color:red; margin-right:30px;" id="">AHT</span>
<span id="seconds" style="font-size:30px; ">00</span>
<span style="font-size:0px; color: #eff4ff;" id="tens">00</span>
</div>
<br><br><br><br>
<div class="wrapper">
<a id="button-start_hold" style="margin-right: 10px; margin-top: -12px" class="btn btn-success">Start </a>
<a id="button-stop_hold" style=" margin-right: 10px;margin-top: -12px" class="btn btn-warning">Stop </a>
<a id="button-reset_hold" class="btn btn-danger" style=" margin-right: 10px;margin-right:30px; margin-top: -12px">Reset </a>
<span style="font-size:30px; color:red; margin-right:30px;" id="">HOLD</span>
<span style="font-size:30px;" id="seconds_hold">00</span><span id="tens_hold" style="font-size:0px; color: #eff4ff;">00</span>
<a id="button-stop"></a>
</div>

In parent page
var team1_timer = 0;
var team1Win = window.open("team1.php","team1");
var resultWin = window.open("result.php","team1");
and in the child pages have
opener.team1_timer = seconds;
and in team1 page have
buttonStart_hold.onclick=function() {
opener.result.buttonStart_hold.onclick();
...
and in result page have
buttonStart_hold.onclick=function() {
opener.team1.buttonStart_hold.onclick();
...
etc

Related

Add value from textbox to counter

I'm learning javascript and I want to create a simple clock. I want for user to be able to change minutes by entering a number in textbox and pressing a button, so when that number is displayed and when the seconds are counted to 60, that displayed number increase by 1, my code won't work, help pls:
var seconds = 0;
var minutes2 = 0;
var rezultat;
let dugme = document.querySelector("#dugme");
var el = document.getElementById("seconds-counter");
var el2 = document.getElementById("minutes-counter");
function incrementSeconds() {
seconds += 1;
if (seconds === 60) {
return seconds = 0;
}
el.innerText = seconds;
}
var cancel = setInterval(incrementSeconds, 1000);
dugme.addEventListener("click", function() {
var minutes = parseInt(document.querySelector("#value").value);
el2.innerText = minutes;
})
function incrementMinutes() {
minutes2 += 1;
if (minutes2 === 60) {
return minutes2 = 0;
}
rezultat = (seconds + minutes2 + minutes);
el2.innerText = rezultat;
}
var cancel = setInterval(incrementMinutes, 60000);
<form>
<input type="text" id="value">
<button id="dugme" type="button">minuti</button>
</form>
<div id="seconds-counter"></div>
<div id="minutes-counter"></div>
</form>
You have a few problems in your code. The main mistake is that your variable minutes is not defined in the function incrementMinutes() where you are trying to use it. You have to calculate it again.
Other improvements that you can make are:
Remove the return in your incrementSeconds and incrementMinutes function
Have only 1 setInterval, and call incrementMinutes when seconds reach 60.
You can see a snippet here below:
var seconds = 0;
var minutes2 = 0;
var rezultat;
let dugme = document.querySelector("#dugme");
var el = document.getElementById("seconds-counter");
var el2 = document.getElementById("minutes-counter");
function incrementSeconds() {
seconds += 1;
if (seconds === 60) {
seconds = 0;
incrementMinutes();
}
el.innerText = seconds;
}
var cancel = setInterval(incrementSeconds, 1000);
dugme.addEventListener("click", function() {
var minutes = parseInt(document.querySelector("#value").value);
el2.innerText = minutes;
})
function incrementMinutes() {
minutes2 += 1;
if (minutes2 === 60) {
minutes2 = 0;
}
rezultat = (minutes2 + parseInt(document.querySelector("#value").value));
el2.innerText = rezultat;
}
<form>
<input type="text" id="value">
<button id="dugme" type="button">minuti</button>
</form>
<div id="seconds-counter"></div>
<div id="minutes-counter"></div>
To show here the behavior I made a minute to 5 seconds.
As a formatting improvement, if you want to show in result min:sec you can do this
min = min < 10 ? "0"+min : min;
seconds = seconds < 10 ? "0" + seconds : seconds;
To build the string with leading zeros.
I have removed the returns because they were not neccessary you can inside reset the value there is no need to return it.
var seconds = 0;
var min = 0;
var rezultat;
let dugme = document.querySelector("#dugme");
var secCounter = document.getElementById("seconds-counter");
var mintCounter = document.getElementById("minutes-counter");
function incrementSeconds() {
seconds += 1;
if (seconds === 60) {
seconds = 0;
}
secCounter.innerText = seconds;
}
var cancel = setInterval(incrementSeconds, 1000);
function incrementMinutes() {
min += 1;
if (min === 60) {
min = 0;
}
tempMin = min;
tempSec = seconds;
min = min < 10 ? "0"+min : min;
seconds = seconds < 10 ? "0" + seconds : seconds;
rezultat = (min+":"+seconds);
mintCounter.innerText = rezultat;
min = tempMin;
seconds = tempSec;
}
// for debugging to 5 sec
var cancel = setInterval(incrementMinutes, 5000);
dugme.addEventListener("click", function() {
var inpMinutes = parseInt(document.querySelector("#value").value);
min = inpMinutes;
mintCounter.innerText = min;
})
<form>
<input type="text" id="value">
<button id="dugme" type="button">minuti</button>
</form>
<div id="seconds-counter"></div>
<div id="minutes-counter"></div>
</form>

Adding Start, Stop, Reset button for timer

I have this count-up timer code and want to add start, stop and reset button. It start right at the page load.
<script type="text/javascript">
var timerVar = setInterval(countTimer, 1000);
var totalSeconds = 0;
function countTimer() {
++totalSeconds;
var hour = Math.floor(totalSeconds /3600);
var minute = Math.floor((totalSeconds - hour*3600)/60);
var seconds = totalSeconds - (hour*3600 + minute*60);
document.getElementById("hour").innerHTML =hour;
document.getElementById("minute").innerHTML =minute;
document.getElementById("seconds").innerHTML =seconds;
}
</script>
It's just some simple manipulation of hour, minute and seconds and making use of clearInterval and setInterval. In my snipper, reset won't stop the timer, but it's easy to make that happen by a few lines of code.
window.onload = () => {
let hour = 0;
let minute = 0;
let seconds = 0;
let totalSeconds = 0;
let intervalId = null;
function startTimer() {
++totalSeconds;
hour = Math.floor(totalSeconds /3600);
minute = Math.floor((totalSeconds - hour*3600)/60);
seconds = totalSeconds - (hour*3600 + minute*60);
document.getElementById("hour").innerHTML =hour;
document.getElementById("minute").innerHTML =minute;
document.getElementById("seconds").innerHTML =seconds;
}
document.getElementById('start-btn').addEventListener('click', () => {
intervalId = setInterval(startTimer, 1000);
})
document.getElementById('stop-btn').addEventListener('click', () => {
if (intervalId)
clearInterval(intervalId);
});
document.getElementById('reset-btn').addEventListener('click', () => {
totalSeconds = 0;
document.getElementById("hour").innerHTML = '0';
document.getElementById("minute").innerHTML = '0';
document.getElementById("seconds").innerHTML = '0';
});
}
<div>Hour: <span id="hour"></span></div>
<div>Minute: <span id="minute"></span></div>
<div>Second: <span id="seconds"></span></div>
<button id="start-btn">Start</button>
<button id="stop-btn">Stop</button>
<button id="reset-btn">Reset</button>
Duplicate of Adding start, stop, and reset buttons for a timer
but just because there is not the HTML part, there is the full answer (html + js thanks to #closure )
(function() {
"use strict";
var secondsLabel = document.getElementById('seconds'),
minutesLabel = document.getElementById('minutes'),
hoursLabel = document.getElementById('hours'), totalSeconds = 0,
startButton = document.getElementById('start'),
stopButton = document.getElementById('stop'),
resetButton = document.getElementById('reset'), timer = null;
startButton.onclick = function() {
if (!timer) {
timer = setInterval(setTime, 1000);
}
};
stopButton.onclick = function() {
if (timer) {
clearInterval(timer);
timer = null;
}
};
resetButton.onclick = function() {
if (timer) {
totalSeconds = 0;
stop();
}
};
function setTime() {
totalSeconds++;
secondsLabel.innerHTML = pad(totalSeconds % 60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
hoursLabel.innerHTML = pad(parseInt(totalSeconds / 3600))
}
function pad(val) {
var valString = val + "";
if (valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
})();
<p id='seconds'></p>
<p id='minutes'></p>
<p id='hours'></p>
<button id='start'>start</button>
<button id='stop'>stop</button>
<button id='reset'>reset</button>
//DOM CACHE
const startBtn = document.querySelector("#start-btn")
const stopBtn = document.querySelector("#stop-btn")
const resetBtn = document.querySelector("#reset-btn")
var minDigits = document.getElementById("min");
var secDigits = document.getElementById("sec");
//INITIALIZING VARIABLES
var hrs = 0;
var mins = 0;
var secs = 0;
var countSec = 0;
var timerVar = null;
//FUNCTIONS=============
function startCounter() {
++countSec;
hrs = Math.floor(countSec /3600);
mins = Math.floor((countSec - hrs*3600)/60);
secs = countSec - (hrs*3600 + mins*60);
if (secs < 10) {
secDigits.innerHTML = "0" + secs;
} else { secDigits.innerHTML = secs; }
minDigits.innerHTML = "0" + mins;
}
startBtn.addEventListener('click', () => {
timerVar = setInterval(startCounter, 1000);
})
stopBtn.addEventListener('click', () => {
if (timerVar)
clearInterval(timerVar);
});
resetBtn.addEventListener('click', () => {
countSec = 0;
secDigits.innerHTML = "00";
minDigits.innerHTML = "00";
clearInterval(timerVar);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Clock JS</title>
</head>
<body>
<div class="container">
<header>
<h1>SIMPLE COUNTER</h1>
<p>At A Time No Time To Check Time</p>
</header>
<div class="clock-face">
<div class="digital-time"></div>
<div class="greeting"></div>
<div class="screen">
<h1 class="digits">
<span id="min" class="minutes">00</span>:<span id="sec" class="seconds">00</span>
</h1>
</div>
<div class="clock-dial">
<button id="start-btn">start</button>
<button id="stop-btn">stop</button>
<button id="reset-btn">reset</button>
</div>
</div>
</div>
<script src="app.js" charset="utf-8"></script>
</body>
</html>

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 display counter value into the output to start a countdown

I'm building a counter and have some issue with. I have a counter field where increment and decrement happen (by default it's 5 minutes). When 'start' button is pressed the final counter's digit should be set as the timer in the output field.
here is my solution:
;(function(){
var output = document.querySelector('#output'),
btn = document.querySelector('button'),
min = 5,
sec = min * 60,
timer;
setCount(min);
function setCount(n){
var c = document.querySelector('#counter'),
increment = c.children[1].children[0],
decrement = c.children[1].children[2],
num = c.children[1].children[1];
increment.onclick = function(){
if(n >= 1) {num.textContent = ++n;}
};
decrement.onclick = function(){
if(n > 1) {num.textContent = --n;}
};
num.textContent = n;
}
function setTimer(){
var currentMin = Math.round((sec - 30) / 60),
currentSec = sec % 60;
if(currentMin >= 0 ) {currentMin = '0' + currentMin;}
if(currentSec <= 9 ) {currentSec = '0' + currentSec;}
if(sec !== 0){sec--;}
timer = setTimeout(setTimer,10); // 10 is for the speedy
output.textContent = currentMin + ':' + currentSec;
}
btn.addEventListener('click', setTimer, false);
})();
here is the link : JS Bin
TL;DR
if(n >= 1) {num.textContent = ++n; sec = n * 60;} // Line 15
...
if(n > 1) {num.textContent = --n; sec = n * 60; } // Line 19
Your timer is deriving it's start min value from the seconds, which is always equal to 5 * 60. You need to update the seconds every time that the + or - is clicked.
(function() {
var output = document.querySelector('#output');
var btn = document.querySelector('button');
var min = 5;
var sec = min * 60;
var timer;
var counter = document.querySelector('#counter ul');
var increment = counter.children[0];
var decrement = counter.children[2];
var number = counter.children[1];
number.textContent = min;
increment.onclick = function() {
min++;
number.textContent = min;
sec = min * 60;
};
decrement.onclick = function() {
min--;
if (min < 1) {
min = 1;
}
sec = min * 60;
number.textContent = min;
};
function setTimer() {
var currentMin = Math.round((sec - 30) / 60),
currentSec = sec % 60;
if (currentMin == 0 && currentSec == 0) {
output.textContent = '00:00';
return;
} else {
timer = setTimeout(setTimer, 10);
}
if (currentMin <= 9) {
currentMin = '0' + currentMin;
}
if (currentSec <= 0) {
currentSec = '0' + currentSec;
}
if (sec !== 0) {
sec--;
}
output.textContent = currentMin + ':' + currentSec;
console.log('currentMin: ' + currentMin);
}
btn.addEventListener('click', setTimer, false);
})();
#wrapper {
width: 300px;
border: 1px solid #f00;
text-align: center;
}
#output {
height: 40px;
line-height: 40px;
border-bottom: 1px solid #f00;
}
h4 {
margin: 10px 0;
}
ul {
margin: 0;
padding: 0;
}
li {
list-style: none;
width: 40px;
height: 40px;
line-height: 40px;
display: inline-block;
border: 1px solid #f00;
}
li:nth-child(odd) {
cursor: pointer;
}
button {
padding: 5px 15px;
margin: 10px 0;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id="wrapper">
<div id="output"></div>
<div id="counter">
<h4>counter</h4>
<ul>
<li>+</li>
<li></li>
<li>-</li>
</ul>
</div>
<button id="start">start</button>
</div>
</body>
</html>

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