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>
Related
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>
In Jquery I want to create multilevel level wise COUNT-UP Timer
For example timer for 1st div ends and timer for next div starts and so on till last div...
Main requirements.
All div will have seconds and minuets count-up counter
Only one div counter will work at a time. One ends and next div will start counter.
Different timer counts are there for different DIVs
Following sample code demo works fine for 1st DIV but not working next all DIVs
Following is my HTMLCODE for multiple DIVs. Where I want to show time up counter for example 00:01 => 00:02 => .. => 00:60 =
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div_1">
<span id="minutes">00</span>:<span id="seconds">00</span>
<div id="done"></div>
</div>
<hr/>
<div id="div_2">
<span id="minutes">00</span>:<span id="seconds">00</span>
<div id="done"></div>
</div>
<hr/>
<div id="div_3">
<span id="minutes">00</span>:<span id="seconds">00</span>
<div id="done"></div>
</div>
<script type="text/javascript">
var totalSeconds = 0;
var div_1 = "div_1";
var timer_1_start = 0;
var timer_1_limit = 05;
var div_2 = "div_2";
var timer_2_start = 05;
var timer_2_limit = 10;
var div_3 = "div_3";
var timer_3_start = 10;
var timer_3_limit = 20;
var div_1_pointer =
setInterval(
function(){
console.log(' ------> Inner function to setInterval for '+div_1);
w3n_setTime(div_1,div_1_pointer,timer_1_start,timer_1_limit);
},
1000 );
/*
var div_2_pointer =
setInterval(
function(){
console.log(' ------> Inner function to setInterval for '+div_1);
w3n_setTime(div_2,div_2_pointer,timer_2_start,timer_2_limit);
},
1000 );
*/
function w3n_setTime(div_id,div_pointer,timer_start,timer_limit){
// console.log(" total mins ==> "+pad(parseInt(totalSeconds / 60)) );
// console.log(" total seconds ==============> "+pad(totalSeconds % 60));
if(parseInt(pad(totalSeconds % 60)) === parseInt(timer_limit)){
console.log(" Timer complete for "+div_id);
clearInterval(div_pointer);
$('#'+div_id+' div#done').html("Done");
}
++totalSeconds;
//secondsLabel.innerHTML = pad(totalSeconds % 60);
//minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
$('#'+div_id+' span#seconds').text(pad(totalSeconds % 60));
$('#'+div_id+' span#minutes').text(pad(parseInt(totalSeconds / 60)));
}
function pad(val) {
var valString = val + "";
if (valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
</script>
01:01
<div id="div_1">
<span id="minutes">00</span>:<span id="seconds">00</span>
<div id="done"></div>
</div>
<hr/>
<div id="div_2">
<span id="minutes">00</span>:<span id="seconds">00</span>
<div id="done"></div>
</div>
<hr/>
<div id="div_3">
<span id="minutes">00</span>:<span id="seconds">00</span>
<div id="done"></div>
</div>
Jquery/JavaScript Code
var totalSeconds = 0;
var div_1 = "div_1";
var timer_1_start = 0;
var timer_1_limit = 05;
var div_2 = "div_2";
var timer_2_start = 05;
var timer_2_limit = 10;
var div_3 = "div_3";
var timer_3_start = 10;
var timer_3_limit = 20;
var div_1_pointer =
setInterval(
function(){
console.log(' ------> Inner function to setInterval for '+div_1);
w3n_setTime(div_1,div_1_pointer,timer_1_start,timer_1_limit);
},
1000 );
/*
var div_2_pointer =
setInterval(
function(){
console.log(' ------> Inner function to setInterval for '+div_1);
w3n_setTime(div_2,div_2_pointer,timer_2_start,timer_2_limit);
},
1000 );
*/
function w3n_setTime(div_id,div_pointer,timer_start,timer_limit){
// console.log(" total mins ==> "+pad(parseInt(totalSeconds / 60)) );
// console.log(" total seconds ==============> "+pad(totalSeconds % 60));
if(parseInt(pad(totalSeconds % 60)) === parseInt(timer_limit)){
console.log(" Timer complete for "+div_id);
clearInterval(div_pointer);
$('#'+div_id+' div#done').html("Done");
}
++totalSeconds;
//secondsLabel.innerHTML = pad(totalSeconds % 60);
//minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
$('#'+div_id+' span#seconds').text(pad(totalSeconds % 60));
$('#'+div_id+' span#minutes').text(pad(parseInt(totalSeconds / 60)));
}
function pad(val) {
var valString = val + "";
if (valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
Issue : I am able to make code work for one DIV only and not for all.
Try following code.
I have modified code to match your requirements. It has only 1 function which will work for all your main DIV.
You have to count and mention length of your DIVs in starting.
Let me know if this works for you.
var totalSeconds = 0;
var game_timer = Array(1,1,1); // time in mins
var game_level = 1; // for start level
var div_pointer =
setInterval(
function(){
var c = game_timer.length; // total game level
if(parseInt(pad(totalSeconds / 60)) == game_timer[game_level-1]) {
$('#div_'+game_level+' div#done').html("Done");
game_level ++;
totalSeconds=0;
}
if(game_level==c && parseInt(pad(totalSeconds / 60)) === parseInt(game_timer[c-1])){
clearInterval(div_pointer);
}
++totalSeconds;
$('#div_'+game_level+' span#seconds').text(pad(totalSeconds % 60));
$('#div_'+game_level+' span#minutes').text(pad(parseInt(totalSeconds / 60)));
},
1000 );
function pad(val) {
var valString = val + "";
if (valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div_1">
<span id="minutes">00</span>:<span id="seconds">00</span>
<div id="done"></div>
</div>
<hr/>
<div id="div_2">
<span id="minutes">00</span>:<span id="seconds">00</span>
<div id="done"></div>
</div>
<hr/>
<div id="div_3">
<span id="minutes">00</span>:<span id="seconds">00</span>
<div id="done"></div>
</div>
I have added a javascript countdown timer to my page but i would like to add more than one timer inside my page. when i add more timers the seconds counter start to skip.
here's my markup code
<div class="fa countdown-timer" style="font-size: x-large">
<span class="fa hrRemaining"></span>:<span class="minRemaining"></span>:<span class="secRemaining"></span>
</div>
<div class="fa countdown-timer" style="font-size: x-large">
<span class="fa hrRemaining"></span>:<span class="minRemaining"></span>:<span class="secRemaining"></span>
</div>
<div class="fa countdown-timer" style="font-size: x-large">
<span class="fa hrRemaining"></span>:<span class="minRemaining"></span>:<span class="secRemaining"></span>
</div>
here's my javascrpit timer
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
var remSeconds = Math.floor(#timeRemaining);
var secondsCounter = Math.floor(remSeconds % 60);
var minutesCounter = Math.floor((remSeconds / 60) % 60);
var hoursCounter = Math.floor((remSeconds / 3600));
function formatNumber(number) {
if (number < 10)
return '0' + number;
else
return '' + number;
}
function startTimers() {
var $timers = $('.countdown-timer');
// See https://api.jquery.com/each/
$timers.each(function() {
// `this` is the current `.countdown-timer` being iterated by jQuery.each()
var $timer = $(this);
var $seconds = $timer.find('.secRemaining');
var $minutes = $timer.find('.minRemaining');
var $hours = $timer.find('.hrRemaining');
$seconds.text(formatNumber(secondsCounter));
$minutes.text(formatNumber(minutesCounter));
$hours.text(formatNumber(hoursCounter));
var _tick = setInterval(function() {
if ((remSeconds) > 0) {
if (hoursCounter > 0) {
if (minutesCounter == 0) {
minutesCounter = 60;
hoursCounter = hoursCounter - 1;
}
}
if (secondsCounter == 0) {
secondsCounter = 60;
minutesCounter = minutesCounter - 1;
}
secondsCounter = secondsCounter - 1;
remSeconds = remSeconds - 1;
$seconds.text(formatNumber(secondsCounter));
$minutes.text(formatNumber(minutesCounter));
$hours.text(formatNumber(hoursCounter));
} else {
clearInterval(_tick);
document.getElementById("tRemaining").innerHTML = "EXPIRED";
}
},
1000);
})
}
startTimers();
</script>
the seconds it skips is directly related to the number of timers i add to the page.
You're sharing these variables
var remSeconds = Math.floor(#timeRemaining);
var secondsCounter = Math.floor(remSeconds % 60);
var minutesCounter = Math.floor((remSeconds / 60) % 60);
var hoursCounter = Math.floor((remSeconds / 3600));
across all the timers. Move the declarations inside this
$timers.each(function() {
function's scope.
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
I am trying to track down the time for a basketball game.
What I need is
A countdown timer with pause and continue.
For that i use the code found at
http://jchavannes.com/jquery-timer/demo
I also need to track the time every player has been in the game. Not all the players are in the game simultaneously.
Problems that i want to solve.
1) Being able to start the countdown timer dynamically from any time. I mean when the page starts the time could be different each time.
2) Being able to add or substract minutes or seconds to the timer when it is stopped.
3) Being able to count up the time of the players that are in the game. That is when they are substituted their counting time should be paused and start counting the time of the players that got in the game.
4) As you can see I create a
var CustomPlayer1 = new (function() { ... }
var CustomPlayer2 = new (function() { ... }
I know it is not the best to create all this for all the players (possibly 24 for the two teams). How can this be created more efficiently?
That for the start. Anything else that may be needed for you to understand and possibly help me do this I will be glad to tell you.
What I have so far is the following. (it is far away for what i need)
<span id="stopwatchplayer1">00:10:00</span>
<br/>
<br/>
<span id="stopwatchplayer2">00:10:00</span>
<br/>
<br/
<h3>Example 2 - Countdown Timer</h3>
<span id="countdown">10:00:00</span>
<form id="example2form">
<input type='button' value='Play/Pause' onclick='Example2.Timer.toggle(), CustomPlayer1.Timer.toggle(), CustomPlayer2.Timer.toggle();' />
<input type='button' value='Stop/Reset' onclick='Example2.resetCountdown();' />
<input type='text' name='startTime' value='300' style='width:30px;' />
</form>
<script>
var CustomPlayer1 = new (function() {
// Stopwatch element on the page
var $stopwatchplayer1;
// Timer speed in milliseconds
var incrementTime = 150;
// Current timer position in milliseconds
var currentTime = 0;
// Start the timer
$(function() {
$stopwatchplayer1 = $('#stopwatchplayer1');
CustomPlayer1.Timer = $.timer(updateTimer, incrementTime, true);
});
// Output time and increment
function updateTimer() {
var timeString = formatTime(currentTime);
$stopwatchplayer1.html(timeString);
currentTime += incrementTime;
}
// Reset timer
this.resetstopwatchplayer1 = function() {
currentTime = 0;
CustomPlayer1.Timer.stop().once();
};
});
var CustomPlayer2 = new (function() {
// Stopwatch element on the page
var $stopwatchplayer2;
// Timer speed in milliseconds
var incrementTime = 150;
// Current timer position in milliseconds
var currentTime = 0;
// Start the timer
$(function() {
$stopwatchplayer2 = $('#stopwatchplayer2');
CustomPlayer2.Timer = $.timer(updateTimer, incrementTime, true);
});
// Output time and increment
function updateTimer() {
var timeString = formatTime(currentTime);
$stopwatchplayer2.html(timeString);
currentTime += incrementTime;
}
// Reset timer
this.resetstopwatchplayer2 = function() {
currentTime = 0;
CustomPlayer2.Timer.stop().once();
};
});
/**
* Example 2 is similar to example 1. The biggest difference
* besides counting up is the ability to reset the timer to a
* specific time. To do this, there is an input text field
* in a form.
*/
var Example2 = new (function() {
var $countdown,
$form, // Form used to change the countdown time
incrementTime = 70,
currentTime = 180000,
updateTimer = function() {
$countdown.html(formatTime(currentTime));
if (currentTime == 0) {
Example2.Timer.stop();
timerComplete();
Example2.resetCountdown();
return;
}
currentTime -= incrementTime / 10;
if (currentTime < 0) currentTime = 0;
},
timerComplete = function() {
//alert('Example 2: Countdown timer complete!');
console.log('Example 2: Countdown timer complete!');
},
init = function() {
$countdown = $('#countdown');
Example2.Timer = $.timer(updateTimer, incrementTime, true);
$form = $('#example2form');
$form.bind('submit', function() {
Example2.resetCountdown();
return false;
});
};
this.resetCountdown = function() {
var newTime = parseInt($form.find('input[type=text]').val()) * 100;
if (newTime > 0) {currentTime = newTime;}
this.Timer.stop().once();
};
$(init);
});
// Common functions
function pad(number, length) {
var str = '' + number;
while (str.length < length) {str = '0' + str;}
return str;
}
function formatTime(time) {
var min = parseInt(time / 6000),
sec = parseInt(time / 100) - (min * 60),
hundredths = pad(time - (sec * 100) - (min * 6000), 2);
return (min > 0 ? pad(min, 2) : "00") + ":" + pad(sec, 2) + ":" + hundredths;
}
<script>
This is the answer i came up with, for anyone interested.
I used the jquery-runner as kasynych suggested yesterday.
github.com/jylauril/jquery-runner.
The answer can be found at http://jsfiddle.net/stefslam/mvx3jooz/7/
STYLE
.in_out {
width: 50px !important;
}
.cls_runner_in {
color: green;
}
.cls_runner_out {
color: red;
}
input[disabled=disabled], input:disabled {
cursor: default;
pointer-events: none;
/*Button disabled - CSS color class*/
color: #c0c0c0 !important;
background-color: #ffffff !important;
}
HTML
<div id="container">
<span id="runner" data-state="1" data-start="600000"></span>
<br />
<br />
<input type='button' id="StartStopButton" value='Play' />
<input type='button' class="edit_runner" data-type="min" data-value="1" data-disable="60000" id="PlusMin" value='+1 Min' />
<input type='button' class="edit_runner" data-type="min" data-value="-1" data-disable="60000" id="MinusMin" value='-1 Min' />
<input type='button' class="edit_runner" data-type="sec" data-value="1" data-disable="1000" id="PlusSec" value='+1 Sec' />
<input type='button' class="edit_runner" data-type="sec" data-value="-1" data-disable="1000" id="MinusSec" value='-1 Sec' />
<input type='button' class="edit_runner" data-type="sec" data-value="10" data-disable="1000" id="PlusSecs" value='+10 Sec' />
<input type='button' class="edit_runner" data-type="sec" data-value="-10" data-disable="1000" id="MinusSecs" value='-10 Sec' />
<br />
<br />Player 1 : <span id="runner1" class="cls_runner cls_runner_in" data-ingame="1" data-start="120000">00:00</span>
<input type='button' class="in_out" data-tospanid="1" value='In' />
<br />
<br />Player 2 : <span id="runner2" class="cls_runner cls_runner_in" data-ingame="1" data-start="221000">00:00</span>
<input type='button' class="in_out" data-tospanid="2" value='In' />
<br />
<br />Player 3 : <span id="runner3" class="cls_runner cls_runner_in" data-ingame="1" data-start="0">00:00</span>
<input type='button' class="in_out" data-tospanid="3" value='In' />
<br />
<br />Player 4 : <span id="runner4" class="cls_runner cls_runner_out" data-ingame="2" data-start="1244">00:00</span>
<input type='button' class="in_out" data-tospanid="4" value='Out' />
<br />
<br />Player 5 : <span id="runner5" class="cls_runner cls_runner_in" data-ingame="1" data-start="10000">00:00</span>
<input type='button' class="in_out" data-tospanid="5" value='In' />
<br />
<br />Player 6 : <span id="runner6" class="cls_runner cls_runner_out" data-ingame="2" data-start="101022">00:00</span>
<input type='button' class="in_out" data-tospanid="6" value='Out' />
<br />
<br />
</div>
JAVASCRIPT
function Custom_millisecondsToString(milliseconds) {
var oneHour = 3600000;
var oneMinute = 60000;
var oneSecond = 1000;
var seconds = 0;
var minutes = 0;
var hours = 0;
var result;
if (milliseconds >= oneHour) {
hours = Math.floor(milliseconds / oneHour);
}
milliseconds = hours > 0 ? (milliseconds - hours * oneHour) : milliseconds;
if (milliseconds >= oneMinute) {
minutes = Math.floor(milliseconds / oneMinute);
}
milliseconds = minutes > 0 ? (milliseconds - minutes * oneMinute) : milliseconds;
if (milliseconds >= oneSecond) {
seconds = Math.floor(milliseconds / oneSecond);
}
milliseconds = seconds > 0 ? (milliseconds - seconds * oneSecond) : milliseconds;
if (hours > 0) {
result = (hours > 9 ? hours : "0" + hours) + ":";
} else {
result = "00:";
result = "";
}
if (minutes > 0) {
result += (minutes > 9 ? minutes : "0" + minutes) + ":";
} else {
result += "00:";
}
if (seconds > 0) {
result += (seconds > 9 ? seconds : "0" + seconds);
} else {
result += "00";
}
//alert (result);
return result;
}
$('.edit_runner').each(function () {
$(this).prop('disabled', true);
});
function checkToDisableButtons() {
var startstop_state = $('#runner').attr('data-state');
//console.log($('#runner').attr('data-state'));
//$('#runner').each(function() { alert($('#runner').attr('data-state')); });
console.log(startstop_state);
$('.edit_runner').each(function () {
$(this).prop('disabled', true);
});
if (startstop_state == 1) {
var runner_start = $('#runner').data('start');
var runner_value = $('#runner').html();
var piece_value = runner_value.split(':');
var current_value_millisecond = (parseFloat(piece_value[0]) * 60 + parseFloat(piece_value[1])) * 1000;
//$('.edit_runner').prop('disabled', true);
console.log('runner_start-current_value_millisecond<60000 = ' + runner_start + '-' + current_value_millisecond + '<' + 60000 + ' = ' + (runner_start - current_value_millisecond));
if (runner_start - current_value_millisecond > 60000) {
//$('.edit_runner[data-type="min"][data-value="1"]').prop('disabled', false);
$('#PlusMin').prop('disabled', false);
//console.log('PlusMin');
}
if (current_value_millisecond > 60000) {
$('#MinusMin').prop('disabled', false);
}
if (runner_start - current_value_millisecond > 1000) {
$('#PlusSec').prop('disabled', false);
}
if (current_value_millisecond > 1000) {
$('#MinusSec').prop('disabled', false);
}
if (runner_start - current_value_millisecond > 10 * 1000) {
$('#PlusSecs').prop('disabled', false);
}
if (current_value_millisecond > 10 * 1000) {
$('#MinusSecs').prop('disabled', false);
}
//alert (current_value_millisecond);
}
}
$("div#container").on('click', '.in_out', function () {
var temp_id;
var temp_action;
temp_id = $(this).data('tospanid');
temp_val = $(this).val();
//alert($(this).data('action')+' - '+$(this).val());
if (temp_val == 'In') {
$('#runner' + temp_id).css("color", "red").removeClass('cls_runner_in').addClass('cls_runner_out');
$(this).val('Out');
$(this).attr('data-action', 2);
} else {
$('#runner' + temp_id).css("color", "green").removeClass('cls_runner_out').addClass('cls_runner_in');
$(this).val('In');
$(this).attr('data-action', 1);
}
});
$('#runner').each(function () {
var $this = $(this);
$this.runner({
countdown: true,
milliseconds: false,
startAt: $this.data('start'), // alternatively you could just write: 10*60*1000 = 10 minutes data-start="10*60*1000"
stopAt: 0, // 2(min) * 60(sec) * 1000(ms) = 120000
format: function millisecondsToString(milliseconds) {
return Custom_millisecondsToString(milliseconds);
}
}).on('runnerFinish', function (eventObject, info) {
$('.cls_runner_in, .cls_runner_out').each(function () {
$(this).runner('stop');
});
});
});
$('.cls_runner').each(function () {
var $this = $(this);
//console.log($this.data('start'));
$this.runner({
milliseconds: false,
startAt: $this.data('start'), // $(this).data('start')
//stopAt: $('#runner').data('start')
format: function millisecondsToString(milliseconds) {
return Custom_millisecondsToString(milliseconds);
}
});
});
//$('.cls_runner_in').runner('toggle');
//$('.cls_runner_out').runner('stop');
$("div#container").on('click', '#StartStopButton', function () {
$('#runner').runner('toggle');
$(this).val($(this).val() == 'Play' ? 'Pause' : 'Play');
$(this).attr('data-state', $(this).attr('data-state') == '1' ? '2' : '1');
$('#runner').attr('data-state', $(this).attr('data-state') == '1' ? '2' : '1');
//console.log($(this).data('state'));
checkToDisableButtons();
$('.cls_runner_in').each(function () {
var $this = $(this);
//console.log($this.data('start'));
$this.runner('toggle');
});
//$('.cls_runner_out').runner('stop');
});
$("div#container").on('click', '.edit_runner', function () {
var current_type;
var current_value;
//$("#my_time").val($('.runner').runner('getCurrentTime'));
current_time = $('#runner').html();
current_type = $(this).data('type');
current_value = $(this).data('value');
current_cls_value = $(this).data('value') * (-1);
//alert (current_type+' - '+current_value);
var piece = current_time.split(':');
var current_millisecond = (parseFloat(piece[0]) * 60 + parseFloat(piece[1])) * 1000;
//alert (piece[0]+'*'+60+' + '+piece[1]);
//alert (current_millisecond);
if (current_type == 'min') {
var new_runner_time = current_millisecond + current_value * 60000;
$('.cls_runner_in').each(function () {
var $this = $(this);
current_cls_time = $this.html();
//console.log($this.data('start'));
var piece_cls = current_cls_time.split(':');
var current_cls_millisecond = (parseFloat(piece_cls[0]) * 60 + parseFloat(piece_cls[1])) * 1000;
var new_cls_time = current_cls_millisecond + current_cls_value * 60000;
$this.runner({
milliseconds: false,
startAt: new_cls_time,
format: function millisecondsToString(milliseconds) {
return Custom_millisecondsToString(milliseconds);
}
});
});
} else {
var new_runner_time = current_millisecond + current_value * 1000;
$('.cls_runner_in').each(function () {
var $this = $(this);
current_cls_time = $this.html();
//console.log($this.data('start'));
var piece_cls = current_cls_time.split(':');
var current_cls_millisecond = (parseFloat(piece_cls[0]) * 60 + parseFloat(piece_cls[1])) * 1000;
var new_cls_time = current_cls_millisecond + current_cls_value * 1000;
$this.runner({
milliseconds: false,
startAt: new_cls_time,
format: function millisecondsToString(milliseconds) {
return Custom_millisecondsToString(milliseconds);
}
});
});
}
//alert (mins);
$('#runner').runner({
countdown: true,
milliseconds: false,
startAt: new_runner_time, // alternatively you could just write: 10*60*1000 = 10 minutes data-start="10*60*1000"
stopAt: 0, // 2(min) * 60(sec) * 1000(ms) = 120000
format: function millisecondsToString(milliseconds) {
return Custom_millisecondsToString(milliseconds);
}
});
checkToDisableButtons();
});