stopwatch clear variable javascript - javascript

Hey all I'm extremely unfamiliar in using javascript... I just need help clearing the time (this should stop the time then clear it) in my script. See: function clear() thanks :) if you have any suggestions in merging the stop\start button into one function that'd be appreciated too. thank you again!
<script type='text/javascript'>
var clsStopwatch = function () {
var startAt = 0;
var lapTime = 0;
var now = function () {
return (new Date()).getTime();
};
this.start = function () {
startAt = startAt ? startAt : now();
};
this.stop = function () {
lapTime = startAt ? lapTime + now() - startAt : lapTime;
startAt = 0;
};
this.time = function () {
return lapTime + (startAt ? now() - startAt : 0);
};
};
var x = new clsStopwatch();
var $time;
var clocktimer;
function pad(num, size) {
var s = "0000" + num;
return s.substr(s.length - size);
}
function formatTime(time) {
var h = m = s = ms = 0;
var newTime = '';
m = Math.floor(time / (60 * 1000));
time = time % (60 * 1000);
s = Math.floor(time / 1000);
ms = time % 1000;
newTime = pad(m, 2) + ':' + pad(s, 2) + ':' + pad(ms, 2);
return newTime;
}
function show() {
$time = document.getElementById('time');
update();
}
function update() {
$time.innerHTML = formatTime(x.time());
}
function start() {
clocktimer = setInterval("update()", 1);
x.start();
}
function stop() {
x.stop();
document.getElementById('counter').value = formatTime(x.time());
clearInterval(clocktimer);
}
function clear() {
x.stop();
????????? this is the function i need help on
}
</script>
html:
<body onload="show();">
<form action="submit.php" method="post"/>
Time: <span id="time"></span><br/>
<!--<input type="text" name-"time">-->
<input type="button" value="Start" onclick="start();">
<input type="button" value="Stop" onclick="stop();">
<input type="button" value="Clear" onclick="clear();">
<input type="submit" value="Save" onclick="stop();">
<br/><br/>

You, forgot to put show() in the start() function
Here is the working fiddle http://jsfiddle.net/64gFm/
Change the clear() function to clearWatch() as clear is an inbult function
New Updated Js Fiddle http://jsfiddle.net/64gFm/1/
function clearWatch() {
x.stop();
x.clear();
clearInterval(clocktimer);
update();
}
Hope, it may help you. Have anice day. :)

Related

stop interval inside a function

I have this script that runs a soccer game clock,
when I click the start button everything is working properly
but I can't stop the clock.
var count;
function gameClock() {
var minutesLabel = document.getElementById("minutes");
var secondsLabel = document.getElementById("seconds");
var totalSeconds = 0;
var count = setInterval(function() {
setTime()
}, 1000);
function setTime() {
++totalSeconds;
secondsLabel.innerHTML = pad(totalSeconds % 60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
}
function pad(val) {
var valString = val + "";
if (valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
}
//Start Stop Game Clock
$(document).on('click', '#f_start', function() {
$("#half_name").text('FIRST HALF');
gameClock();
// localStorage.setItem('first_half_click', getTime());
// localStorage.setItem('half', 1);
})
$(document).on('click', '#f_stop', function() {
clearInterval(count);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="col-2">
<button class="btn btn-success" id="f_start"> START</button>
</div>
<div class="col-2">
<button class="btn btn-danger" id="f_stop"> STOP</button>
</div>
You are redeclaring the count global variable inside the gameClock method which means it's scope is only in that function. change the assignment to use the global count variable instead of the useless local variable.
var count = setInterval(function() {
setTime()
}, 1000);
//to
count = setInterval(function() {
setTime()
}, 1000);

How can I fix the stop-start process within this Javascript stopwatch-clock?

I have a JavaScript stopwatch here, I require the start-stop button to keep the same time when continuing.
Currently, if I stop and continue the clock diff is something ridiculous such as '-19330839:-3:-53'
Can anyone explain how this is fixed?
I have various method stopwatches made; however I would rather use real date time instead of a counter, this is because (I have tested after being made aware of this) that counters are very inaccurate over a period of time.
Any help is much appreciated.
html:
Please ignore the reset button for now. I will configure this later.
<input id="startstopbutton" class="buttonZ" style="width: 120px;" type="button" name="btn" value="Start" onclick="startstop();">
<input id="resetbutton" class="buttonZ" style="width: 120px;" type="button" name="btnRst1" id='btnRst1' value="Reset" onclick="resetclock();"/>
<div id="outputt" class="timerClock" value="00:00:00">00:00:00</div>
JS:
const outputElement = document.getElementById("outputt");
var startTime = 0;
var running = false;
var splitcounter = 0;
function startstop() {
if (running == false) {
running = true;
startTime = new Date(sessionStorage.getItem("time"))
if (isNaN(startTime)) startTime = Date.now();
startstopbutton.value = 'Stop';
document.getElementById("outputt").style.backgroundColor = "#2DB37B";
updateTimer();
} else {
running = false;
logTime();
startstopbutton.value = 'Start';
document.getElementById("outputt").style.backgroundColor = "#B3321B";
}
}
function updateTimer() {
if (running == true) {
let differenceInMillis = Date.now() - startTime;
sessionStorage.setItem("time", differenceInMillis)
let {
hours,
minutes,
seconds
} = calculateTime(differenceInMillis);
let timeStr = `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`;
outputElement.innerText = timeStr;
requestAnimationFrame(updateTimer);
}
}
function calculateTime(milliS) {
const SECONDS = 1000; // should be 1000 - only 10 to speed up the timer
const MINUTES = 60;
const HOURS = 60;
const RESET = 60;
let hours = Math.floor(milliS / SECONDS / MINUTES / HOURS);
let minutes = Math.floor(milliS / SECONDS / MINUTES) % RESET;
let seconds = Math.floor(milliS / SECONDS) % RESET;
return {
hours,
minutes,
seconds
};
}
function pad(time) {
return time.toString().padStart(2, '0');
}
I just need the timer to continue on from where it was stopped at.
Issue with your code:
You start with initial value for sessionStorage as Date.now but then save difference on update.
You interact a lot with session storage. Any communication with external API is expensive. Instead use local variables and find an event to initialise values.
Time difference logic is a bit off.
Date.now - startTime does not considers the difference between stop action and start action.
You can use this logic: If startTime is defined, calculate difference and add it to start time. If not, initialise it to Date.now()
Suggestions:
Instead of adding styles, use classes. That will help you in reset functionality
Define small features and based on it, define small functions. That would make reusability easy
Try to make functions independent by passing arguments and only rely on them. That way you'll reduce side-effect
Note: as SO does not allow access to Session Storage, I have removed all the related code.
const outputElement = document.getElementById("outputt");
var running = false;
var splitcounter = 0;
var lastTime = 0;
var startTime = 0;
function logTime() {
console.log('Time: ', lastTime)
}
function resetclock() {
running = false;
startTime = 0;
printTime(Date.now())
applyStyles(true)
}
function applyStyles(isReset) {
startstopbutton.value = running ? 'Stop' : 'Start';
document.getElementById("outputt").classList.remove('red', 'green')
if (!isReset) {
document.getElementById("outputt").classList.add(running ? 'red' : 'green')
}
}
function startstop() {
running = !running;
applyStyles();
if (running) {
if (startTime) {
const diff = Date.now() - lastTime;
startTime = startTime + diff;
} else {
startTime = Date.now()
}
updateTimer(startTime);
} else {
lastTime = Date.now()
logTime();
}
}
function printTime(startTime) {
let differenceInMillis = Date.now() - startTime;
let {
hours,
minutes,
seconds
} = calculateTime(differenceInMillis);
let timeStr = `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`;
outputElement.innerText = timeStr;
}
function updateTimer(startTime) {
if (running == true) {
printTime(startTime)
requestAnimationFrame(() => updateTimer(startTime));
}
}
function calculateTime(milliS) {
const SECONDS = 1000; // should be 1000 - only 10 to speed up the timer
const MINUTES = 60;
const HOURS = 60;
const RESET = 60;
let hours = Math.floor(milliS / SECONDS / MINUTES / HOURS);
let minutes = Math.floor(milliS / SECONDS / MINUTES) % RESET;
let seconds = Math.floor(milliS / SECONDS) % RESET;
return {
hours,
minutes,
seconds
};
}
function pad(time) {
return time.toString().padStart(2, '0');
}
.red {
background-color: #2DB37B
}
.green {
background-color: #B3321B
}
<input id="startstopbutton" class="buttonZ" style="width: 120px;" type="button" name="btn" value="Start" onclick="startstop();">
<input id="resetbutton" class="buttonZ" style="width: 120px;" type="button" name="btnRst1" id='btnRst1' value="Reset" onclick="resetclock();" />
<div id="outputt" class="timerClock" value="00:00:00">00:00:00</div>
simple stopwatch example
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<input class="startstop" style="width: 120px;" type="button" value="Start" onclick="startstop();">
<input class="reset" style="width: 120px;" type="button" value="Reset" onclick="reset();"/>
<div class="timerClock" value="00:00:00">00:00:00</div>
<script type="text/javascript">
var second = 0
var minute = 0
var hour = 0
var interval
var status = false
var element = document.querySelector('.startstop')
var clock = document.querySelector('.timerClock')
var string = ''
function startstop()
{
if(status == 'false')
{
element.value = 'Stop'
clock.style.backgroundColor = "#2DB37B";
status = true
interval = setInterval(function()
{
string = ''
second += 1
if(second >= 60)
{
minute += 1
second = 0
}
if(minute >= 60)
{
hour += 1
minute = 0
}
if(hour < 10)
string += `0${hour}:`
else
string += `${hour}:`
if(minute < 10)
string += `0${minute}:`
else
string += `${minute}:`
if(second < 10)
string += `0${second}`
else
string += `${second}`
clock.innerHTML = string
},1000)
}
else
{
clock.style.backgroundColor = "#B3321B";
element.value = 'Start'
status = false
clearInterval(interval)
}
}
function reset()
{
second = 0
minute = 0
hour = 0
status = false
element.value = 'Start'
clearInterval(interval)
clock.innerHTML = `00:00:00`
clock.style.backgroundColor = "transparent";
}
</script>
</body>
</html>
One thing to know about requestAnimationFrame is that it returns an integer that is a reference to the next animation. You can use this to cancel the next waiting animation with cancelAnimationFrame.
As mentioned by #Rajesh, you shouldn't store the time each update, as it will stop the current process for a (very) short while. Better in that case to fire an event, preferably each second, that will wait until it can run. I haven't updated the code to take that into account, I only commented it away for now.
It's also better to use classes than updating element styles. I wrote sloppy code that overwrites all classes on the #outputt element (it's spelled "output"). That's bad programming, because it makes it impossible to add other classes, but it serves the purpose for now. #Rajesh code is better written for this purpose.
I added two variables - diffTime and animationId. The first one corrects startTime if the user pauses. The second one keeps track if there is an ongoing timer animation.
I refactored your style updates into a method of its own. You should check it out, because it defines standard values and then changes them with an if statement. It's less code than having to type document.getElementById("outputt").style... on different rows.
I also added a resetclock method.
const outputElement = document.getElementById("outputt");
var startTime = 0;
var diffTime = 0;
var animationId = 0;
function startstop() {
const PAUSED = 0;
let paused = animationId == PAUSED;
//diffTime = new Date(sessionStorage.getItem("time")) || 0;
startTime = Date.now() - diffTime;
if (paused) {
updateTimer();
} else {
cancelAnimationFrame(animationId);
animationId = PAUSED;
}
updateTimerClass(paused);
}
function updateTimerClass(paused) {
var outputClass = 'red';
var buttonText = 'Start';
if (paused) {
outputClass = 'green';
buttonText = 'Stop';
}
startstopbutton.value = buttonText;
outputElement.classList = outputClass;
}
function updateTimer() {
let differenceInMillis = Date.now() - startTime;
//sessionStorage.setItem("time", differenceInMillis)
let {
hours,
minutes,
seconds
} = calculateTime(differenceInMillis);
let timeStr = `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`;
outputElement.innerText = timeStr;
diffTime = differenceInMillis;
animationId = requestAnimationFrame(updateTimer);
}
function calculateTime(milliS) {
const SECONDS = 1000; // should be 1000 - only 10 to speed up the timer
const MINUTES = 60;
const HOURS = 60;
const RESET = 60;
let hours = Math.floor(milliS / SECONDS / MINUTES / HOURS);
let minutes = Math.floor(milliS / SECONDS / MINUTES) % RESET;
let seconds = Math.floor(milliS / SECONDS) % RESET;
return {
hours,
minutes,
seconds
};
}
function pad(time) {
return time.toString().padStart(2, '0');
}
function resetclock() {
let paused = animationId == 0;
startTime = Date.now();
diffTime = 0;
if (paused) {
const REMOVE_ALL_CLASSES = '';
outputElement.className = REMOVE_ALL_CLASSES;
outputElement.innerText = '00:00:00';
}
}
#outputt.green {
background-color: #2DB37B;
}
#outputt.red {
background-color: #B3321B;
}
<input id="startstopbutton" class="buttonZ" style="width: 120px;" type="button" name="btn" value="Start" onclick="startstop();">
<input id="resetbutton" class="buttonZ" style="width: 120px;" type="button" name="btnRst1" id='btnRst1' value="Reset" onclick="resetclock();"/>
<div id="outputt" class="timerClock" value="00:00:00">00:00:00</div>
class Stopwatch {
constructor(display, results) {
this.running = false;
this.display = display;
this.results = results;
this.laps = [];
this.reset();
this.print(this.times);
}
reset() {
this.times = [ 0, 0, 0 ];
}
click(){
var x=document.getElementById('ctrl');
if(x.value=="start"){
this.start();
x.value="stop";
document.getElementById("outputt").style.backgroundColor = "#2DB37B";
}
else{
x.value="start";
this.stop();
document.getElementById("outputt").style.backgroundColor = "#B3321B";
}
}
start() {
if (!this.time) this.time = performance.now();
if (!this.running) {
this.running = true;
requestAnimationFrame(this.step.bind(this));
}
}
stop() {
this.running = false;
this.time = null;
}
resets() {
document.getElementById("outputt").style.backgroundColor = "#2DB37B";
if (!this.time) this.time = performance.now();
if (!this.running) {
this.running = true;
requestAnimationFrame(this.step.bind(this));
}
this.reset();
}
step(timestamp) {
if (!this.running) return;
this.calculate(timestamp);
this.time = timestamp;
this.print();
requestAnimationFrame(this.step.bind(this));
}
calculate(timestamp) {
var diff = timestamp - this.time;
// Hundredths of a second are 100 ms
this.times[2] += diff / 1000;
// Seconds are 100 hundredths of a second
if (this.times[2] >= 100) {
this.times[1] += 1;
this.times[2] -= 100;
}
// Minutes are 60 seconds
if (this.times[1] >= 60) {
this.times[0] += 1;
this.times[1] -= 60;
}
}
print() {
this.display.innerText = this.format(this.times);
}
format(times) {
return `\
${pad0(times[0], 2)}:\
${pad0(times[1], 2)}:\
${pad0(Math.floor(times[2]), 2)}`;
}
}
function pad0(value, count) {
var result = value.toString();
for (; result.length < count; --count)
result = '0' + result;
return result;
}
function clearChildren(node) {
while (node.lastChild)
node.removeChild(node.lastChild);
}
let stopwatch = new Stopwatch(
document.querySelector('.stopwatch'),
document.querySelector('.results'));
<input type="button" id="ctrl" value="start" onClick="stopwatch.click();">
<input type="button" value="Reset" onClick="stopwatch.resets();">
<div id="outputt" class="stopwatch"></div>

Passing a Javascript Variable to a Rails form_for hidden_field

I have borrowed a fairly complex JS stopwatch and am trying to report the resulting time to my Rails app's database. I have consulted many similar SO posts, but haven't been able to get it working.
Here is my ERB:
<%= form_for #new_log do |f| %>
...
<div class="row text-center">
<div class="btn-white" id="startTime" style="display: inline-block;">
<h4 value="start" onclick="start();">Start Timer</h4>
</div>
<div style="display: inline-block;">
<span id="time" style="color: white"></span><br>
<span class="btn-white" value="reset" onclick="reset()">Reset</span>
</div>
<div class="btn-white" id="stopTime" style="display: inline-block;">
<h4 value="stop" onclick="stop();">Stop Timer</h4>
</div>
<%= f.hidden_field :duration, id: "duration" %>
...
<%= f.submit "Record My Log", id: "submit", class: "btn-ghost" %>
<% end %>
Here's the JS:
<script> // STOPWATCH
var clsStopwatch = function() {
// Private vars
var startAt = 0; // Time of last start / resume. (0 if not running)
var lapTime = 0; // Time on the clock when last stopped in milliseconds
var now = function() {
return (new Date()).getTime();
};
// Public methods
// Start or resume
this.start = function() {
startAt = startAt ? startAt : now();
};
// Stop or pause
this.stop = function() {
// If running, update elapsed time otherwise keep it
lapTime = startAt ? lapTime + now() - startAt : lapTime;
startAt = 0; // Paused
};
// Reset
this.reset = function() {
lapTime = startAt = 0;
};
// Duration
this.time = function() {
return lapTime + (startAt ? now() - startAt : 0);
};
};
var x = new clsStopwatch();
var $time;
var clocktimer;
function pad(num, size) {
var s = "0000" + num;
return s.substr(s.length - size);
}
function formatTime(time) {
var h = m = s = ms = 0;
var newTime = '';
h = Math.floor( time / (60 * 60 * 1000) );
time = time % (60 * 60 * 1000);
m = Math.floor( time / (60 * 1000) );
time = time % (60 * 1000);
s = Math.floor( time / 1000 );
ms = time % 1000;
newTime = pad(h, 2) + ':' + pad(m, 2) + ':' + pad(s, 2) + ':' + pad(ms, 3);
return newTime;
// THIS IS THE PART I ADDED, WHICH IS NOT WORKING
$('#submit').on('click', function() {
$('#duration').val(newTime);
});
// MY ADDITION ENDS HERE
}
function show() {
$time = document.getElementById('time');
update();
}
function update() {
$time.innerHTML = formatTime(x.time());
}
function start() {
clocktimer = setInterval("update()", 1);
x.start();
}
function stop() {
x.stop();
clearInterval(clocktimer);
}
function reset() {
stop();
x.reset();
update();
}
</script>
Hopefully this will be a fairly simple fix for someone with a better eye for JS than mine. Currently the stopwatch and the form submission still work, but the :duration still gets recorded into the database as nil.
Thanks for any help you can spare!
Your event method never gets called because the formatTime function returns newTime before it can reach it. Try moving the click function out of the formatTime function. Remember to set the return value of formatTime to a variable because newTime will be out of scope.

Adding start, stop, and reset buttons for a timer

I'm making a timer and have it working already one load. I want to add a start, stop, and reset button to it. This is my code as is atm.
(function() {
"use strict";
var secondsLabel = document.getElementById('seconds'),
minutesLabel = document.getElementById('minutes'),
hoursLabel = document.getElementById('hours'),
totalSeconds = 0,
startButton = document.getElementById('start'),
resetButton = document.getElementById('reset'),
onOff = 0;
startButton.onclick = function() {
onOff = 1;
};
resetButton.onclick = function() {
totalSeconds = 0;
onOff = 0;
};
if ( onOff == 1 ) {
setInterval( setTime, 1000 );
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;
}
}
}
})();
The buttons are not working atm however. I'm not sure if this the best solution for the goal as well, so suggestions are welcome.
(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;
}
}
})();
<html>
<head>
<script type="text/javascript">
var c=0;
var t;
var timer_is_on=0;
function timedCount()
{
document.getElementById('txt').value=c;
c=c+1;
t=setTimeout("timedCount()",1000);
}
function doTimer()
{
if (!timer_is_on)
{
timer_is_on=1;
timedCount();
}
}
function stopCount()
{
clearTimeout(t);
timer_is_on=0;
}
</script>
</head>
<body>
<form>
<input type="button" value="Start count!" onclick="doTimer()" />
<input type="text" id="txt" />
<input type="button" value="Stop count!" onclick="stopCount()" />
</form>
<p>
Click on the "Start count!" button above to start the timer. The input field will count forever, starting at 0. Click on the "Stop count!" button to stop the counting. Click on the "Start count!" button to start the timer again.
</p>
</body>
</html>

Need help with stopping setTimeout() timers

I have an html table listing processes... one per row. I'd like to add separate timers to each row to show elapsed time of each process as each one starts.
I need help stopping the timers once a process is complete for any given row, and to automatically stop the timer after 2 hours if a process runs that long.
The code below allows me to run multiple timers but I do not know how to write a function to stop the individual timers, or to stop a timer after two ours of run time.
Can anyone help me with this?
Thanks,
Jeff
<html>
<head>
<script type="text/javascript">
function timer(elementId){
this.startTime = new Date();
this.hours = 0, this.minutes = 0, this.seconds = 0, this.borrowed = 0;
this.update(elementId);
}
timer.prototype.getDifference=function(start,now,MAX){
var diff = now - start - this.borrowed;
this.borrowed = 0;
if ( diff > -1 ) return diff;
this.borrowed = 1;
return (MAX + diff);
}
timer.prototype.timerPad=function(){
this.seconds = this.addZero(this.seconds);
this.minutes = this.addZero(this.minutes);
this.hours = this.addZero(this.hours);
}
timer.prototype.addZero=function(value){
return value < 10 ? ("0" + value) : value;
}
timer.prototype.update=function(elementId){
var currTime = new Date();
var startTime = this.startTime;
this.seconds = this.getDifference(startTime.getSeconds(), currTime.getSeconds(), 60);
this.minutes = this.getDifference(startTime.getMinutes(), currTime.getMinutes(), 60);
this.hours = this.getDifference(startTime.getHours(), currTime.getHours(), 2);
this.timerPad();
var e = document.getElementById(elementId);
e.innerHTML = this.hours + ":" + this.minutes + ":" + this.seconds;
var self = this;
this.timer = setTimeout(function(){self.update(elementId);},1000);
}
</script>
</head>
<body>
<button type="button" onClick="javascript:new timer('timer1');">Start!</button>
<button type="button" onClick="">Stop!</button>
<div id="timer1"></div><p>
<button type="button" onClick="javascript:new timer('timer2');">Start!</button>
<button type="button" onClick="">Stop!</button>
<div id="timer2"></div>
</body>
</html>
Having the new timer object created in the inline event handler will be a problem to deal with two different controls.
You can change the HTML/JS as follows:
Javascript:(added startTimer and stopTimer functions along with a stop method to timer prototype)
<script type="text/javascript">
function timer(elementId){
this.startTime = new Date();
this.hours = 0, this.minutes = 0, this.seconds = 0, this.borrowed = 0;
this.update(elementId);
var that = this;
//setTimeout(function(){that.stop()}, 7200000) //Uncomment this to enable autostop after 2 hours
}
timer.prototype.getDifference=function(start,now,MAX){
var diff = now - start - this.borrowed;
this.borrowed = 0;
if ( diff > -1 ) return diff;
this.borrowed = 1;
return (MAX + diff);
}
timer.prototype.timerPad=function(){
this.seconds = this.addZero(this.seconds);
this.minutes = this.addZero(this.minutes);
this.hours = this.addZero(this.hours);
}
timer.prototype.addZero=function(value){
return value < 10 ? ("0" + value) : value;
}
timer.prototype.stop=function(){
clearTimeout(this.timerKey);
}
timer.prototype.update=function(elementId){
var currTime = new Date();
var startTime = this.startTime;
this.seconds = this.getDifference(startTime.getSeconds(), currTime.getSeconds(), 60);
this.minutes = this.getDifference(startTime.getMinutes(), currTime.getMinutes(), 60);
this.hours = this.getDifference(startTime.getHours(), currTime.getHours(), 2);
this.timerPad();
var e = document.getElementById(elementId);
e.innerHTML = this.hours + ":" + this.minutes + ":" + this.seconds;
var self = this;
this.timerKey = setTimeout(function(){self.update(elementId);},1000);
}
var timers = [];
function startTimer(timerName) {
var timerObj = new timer(timerName);
timers[timerName] = timerObj;
}
function stopTimer(timerName) {
var timerObj = timers[timerName];
if(timerObj) timerObj.stop();
}
</script>
HTML:(Changed the onclick event handlers to call startTimer/stopTimer passing the timer name)
<button type="button" onclick="javascript:startTimer('timer1');">
Start!</button>
<button type="button" onclick="javascript:stopTimer('timer1');">
Stop!</button>
<div id="timer1">
</div>
<p>
<button type="button" onclick="javascript:startTimer('timer2');">
Start!</button>
<button type="button" onclick="javascript:stopTimer('timer2');">
Stop!</button>
<div id="timer2">
</div>
Edit:(autostop after 2 hrs)
Change your timer method definition to as follows:
function timer(elementId){
this.startTime = new Date();
this.hours = 0, this.minutes = 0, this.seconds = 0, this.borrowed = 0;
var that = this;
setTimeout(function(){that.stop()}, 7200000);
}
You could:
Create an object to store setTimeout variables for specific timers
Create a factory function to create new timers, store setTimeout variables into global object
Create destructor function to cancel timers (if they exist)
var timers = {};
function createTimer(elementId) {
var timer = new timer(elementId);
timers[elementId] = setTimeout((function() {timer.update();}), 1000);
}
function destroyTimer(elementId) {
if (elementId in timers) {
clearTimeout(timers[elementId]);
}
}
Obviously, this might have to be updated a bit to work in your situation.

Categories