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.
Related
I'm making a simple clock app that displays the current time as a way of practicing my JS in combination with HTML & CSS (I'm quite new to coding).
My code works fine, but I'm confused about an unexpected result I got when experimenting. I created a class, instantiated it, and then tried to print the inner HTML that my display() method was inserting into a pre-existing div (id="time").
See below:
class Clock {
constructor() {
this.date = new Date;
this.day = this.date.getDate();
this.secs = this.date.getSeconds();
this.mins = this.date.getMinutes();
this.hours = this.date.getHours();
}
update(increment) {
this.secs += increment;
if (this.secs >= 60) {
this.secs = this.secs - 60;
this.mins++;
}
if (this.mins >= 60) {
this.mins = 0;
this.hours++;
}
if (this.hours >= 24) {
this.hours = 0;
}
}
display() {
this.update(1);
let HMS = [this.hours, this.mins, this.secs].map(item => item < 10 ? `0${item}` : item);
document.getElementById('time').innerHTML = `${HMS[0]} : ${HMS[1]} : ${HMS[2]}`;
}
run() {
setInterval(this.display.bind(this), 1000);
}
}
// TESTING
let clock = new Clock; // Create new clock instance
clock.run(); // Clock is running
let time = document.getElementById('time'); // Retrieving element that contains the time
console.log(time.innerHTML);
<div id="time"></div>
Gives empty string! Why does it not log the HTML I inserted in my display() method?
As above, I don't understand why the HTML that's inserted into my 'time' div as part of the display() method isn't recognized when I console.log it. I feel there's a concept that I'm not grasping in this example, and I can't figure out what it is.
Could someone please help explain it?
Many thanks!
setInterval does not fire immediately, it will only start firing after the first delay (1 second).
As such at the moment your console.log fires before there is anything within the time div.
One way around this is to call this.display and then set the setInterval.
Example to demonstrate the current problem
In this example I have added some text inside the time div, you will see when you run the example that text displays for a second and is also logged to the console.
I then log the time div contents 1.5 seconds later and it then shows the current time.
class Clock {
constructor() {
this.date = new Date;
this.day = this.date.getDate();
this.secs = this.date.getSeconds();
this.mins = this.date.getMinutes();
this.hours = this.date.getHours();
}
update(increment) {
this.secs += increment;
if (this.secs >= 60) {
this.secs = this.secs - 60;
this.mins++;
}
if (this.mins >= 60) {
this.mins = 0;
this.hours++;
}
if (this.hours >= 24) {
this.hours = 0;
}
}
display() {
this.update(1);
let HMS = [this.hours, this.mins, this.secs].map(item => item < 10 ? `0${item}` : item);
document.getElementById('time').innerHTML = `${HMS[0]} : ${HMS[1]} : ${HMS[2]}`;
}
run() {
setInterval(this.display.bind(this), 1000);
}
}
// TESTING
let clock = new Clock; // Create new clock instance
clock.run(); // Clock is running
let time = document.getElementById('time'); // Retrieving element that contains the time
console.log(time.innerHTML);
setTimeout(function(){
console.log(time.innerHTML);
}, 1500);
<div id="time">Not Updated Yet</div>
Example to demonstrate for to fix the issue
In this example all I do is call the display() function immediately within your run function and then set up the setInterval. This way the time is set immediately and so can be logged to the console.
class Clock {
constructor() {
this.date = new Date;
this.day = this.date.getDate();
this.secs = this.date.getSeconds();
this.mins = this.date.getMinutes();
this.hours = this.date.getHours();
}
update(increment) {
this.secs += increment;
if (this.secs >= 60) {
this.secs = this.secs - 60;
this.mins++;
}
if (this.mins >= 60) {
this.mins = 0;
this.hours++;
}
if (this.hours >= 24) {
this.hours = 0;
}
}
display() {
this.update(1);
let HMS = [this.hours, this.mins, this.secs].map(item => item < 10 ? `0${item}` : item);
document.getElementById('time').innerHTML = `${HMS[0]} : ${HMS[1]} : ${HMS[2]}`;
}
run() {
this.display();
setInterval(this.display.bind(this), 1000);
}
}
// TESTING
let clock = new Clock; // Create new clock instance
clock.run(); // Clock is running
let time = document.getElementById('time'); // Retrieving element that contains the time
console.log(time.innerHTML);
<div id="time"></div>
class Clock {
constructor() {
this.date = new Date;
this.day = this.date.getDate();
this.secs = this.date.getSeconds();
this.mins = this.date.getMinutes();
this.hours = this.date.getHours();
}
update(increment) {
this.secs += increment;
if (this.secs >= 60) {
this.secs = this.secs - 60;
this.mins++;
}
if (this.mins >= 60) {
this.mins = 0;
this.hours++;
}
if (this.hours >= 24) {
this.hours = 0;
}
}
display() {
this.update(1);
let HMS = [this.hours, this.mins, this.secs].map(item => item < 10 ? `0${item}` : item);
document.getElementById('time').innerHTML = `${HMS[0]} : ${HMS[1]} : ${HMS[2]}`;
}
run() {
setInterval(this.display.bind(this), 1000);
}
}
// TESTING
let clock = new Clock; // Create new clock instance
clock.run(); // Clock is running
let time = document.getElementById('time'); // Retrieving element that contains the time
console.log(time);
<div id="time"></div>
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>
I have been made a count down for 10 items with JavaScript but it was so long for several items.
How can i make this brief?
this code for the only one item.
var time01 = 16360;
function time(){
var hour =Math.floor(time01/3600);
var baghi01=time01%3600;
var min = Math.floor(baghi01/60);
var sec = baghi01%60;
document.getElementById('hour-01').textContent = hour;
document.getElementById('min-01').textContent = min;
document.getElementById('sec-01').textContent = sec;
if(sec<10){
document.getElementById('sec-01').textContent = (`0${sec}`);
}
if(min<10){
document.getElementById('min-01').textContent = (`0${min}`);
}
if(hour<10){
document.getElementById('hour-01').textContent = (`0${hour}`);
}
time01 --;
}
setInterval(time,1000);
You could take a closure over the time and target information.
function time(time, target) {
const format = v => v.toString().padStart(2, 0);
var hourE = document.getElementById(`hour-${target}`),
minE = document.getElementById(`min-${target}`),
secE = document.getElementById(`sec-${target}`);
return function () {
var hour = Math.floor(time / 3600)
baghi01 = time % 3600,
min = Math.floor(baghi01 / 60),
sec = baghi01 % 60;
hourE.innerHTML = format(hour);
minE.innerHTML = format(min);
secE.innerHTML = format(sec);
time--;
};
}
setInterval(time(16360, '01'), 996);
setInterval(time(16360, '02'), 997);
setInterval(time(16360, '03'), 998);
setInterval(time(16360, '04'), 999);
setInterval(time(16360, '05'), 1000);
<span id="hour-01"></span>:<span id="min-01"></span>:<span id="sec-01"></span><br>
<span id="hour-02"></span>:<span id="min-02"></span>:<span id="sec-02"></span><br>
<span id="hour-03"></span>:<span id="min-03"></span>:<span id="sec-03"></span><br>
<span id="hour-04"></span>:<span id="min-04"></span>:<span id="sec-04"></span><br>
<span id="hour-05"></span>:<span id="min-05"></span>:<span id="sec-05"></span><br>
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. :)
I have this code:
var hour = parseInt(js_arr[j].substring(0, 1));
var min = parseInt(js_arr[j].substring(3, 4));
var seconds = parseInt(js_arr[j].substring(6, 7));
var mil_sec = parseInt(js_arr[j].substring(9, 11));
var time = (hour * 3600000) + (min * 60000) + (seconds * 1000) + mil_sec;
function timeout() {
setTimeout(function () {
if (true) {
document.getElementById('subs').innerHTML = js_arr[i];
i = i + 4;
j = j + 4;
hour = parseInt(js_arr[j].substring(0, 1));
min = parseInt(js_arr[j].substring(3, 4));
seconds = parseInt(js_arr[j].substring(6, 7));
mil_sec = parseInt(js_arr[j].substring(9, 11));
time = (hour * 3600000) + (min * 60000) + (seconds * 1000) + mil_sec;
timeout();
} else {
timeout();
}
}, time);
}
Before javascript code I have an onclick="timeout(); button.
This button allows subtitles to play. What I would also like it to do is to stop these subtitles from playing by clicking on that same button. It would be great if someone could help!
Thanks a lot.
Add a variable that indicates whether the timeout is active. In the timeout()-function, this variable is checked and another loop is only initiated when it is true. To Start and Stop you simply set (and call timeout()) or reset the variable.
var hour = parseInt(js_arr[j].substring(0,1));
var min = parseInt(js_arr[j].substring(3,4));
var seconds = parseInt(js_arr[j].substring(6,7));
var mil_sec = parseInt(js_arr[j].substring(9,11));
var time = (hour*3600000)+(min*60000)+(seconds*1000)+mil_sec;
var timeOutRunning = false;
function startTimeOut() {
timeOutRunning = true;
timeout();
}
function stopTimeOut() {
timeOutRunning = false;
}
function timeout() {
if(timeOutRunning) {
setTimeout(function() {
document.getElementById('subs').innerHTML = js_arr[i];
i=i+4;
j=j+4;
hour = parseInt(js_arr[j].substring(0,1));
min = parseInt(js_arr[j].substring(3,4));
seconds = parseInt(js_arr[j].substring(6,7));
mil_sec = parseInt(js_arr[j].substring(9,11));
time = (hour*3600000)+(min*60000)+(seconds*1000)+mil_sec;
timeout();
}, time);
}
}
And then the onclick-function:
onclick="if(timeOutRunning) { stopTimeOut(); } else { startTimeOut(); }"