Adding start, stop, and reset buttons for a timer - javascript

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>

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>

Adding Start, Stop, Reset button for timer

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

Countdown timer javascript mins into hours

I'm a beginner in JavaScript, I wrote a countdown timer, but I don't know how to convert the mins into hours. I think its not to hard, but I can't do it, whenever I wrote new rows its not working. Here is my code:
var minutesRemaining;
var secondsRemaining;
var intervalHandle;
function resetPage() {
document.getElementById('inputArea').style.display = 'block';
//hide pause button by default
document.getElementById("pauseArea").style.display = "none";
//hide resume button
document.getElementById("resumeArea").style.display = "none";
}
function resumeCountdown() {
tick();
intervalHandle = setInterval(tick, 1000);
//hide resume button when resuming
document.getElementById("resumeArea").style.display = "none";
//show resume button;
document.getElementById("pauseArea").style.display = "block";
return;
}
function pauseCountdown() {
clearInterval(intervalHandle);
document.getElementById("pauseArea").style.display = "none";
document.getElementById("resumeArea").style.display = "block";
return;
}
function tick() {
//grab h1
var timeDisplay = document.getElementById('time');
//turn seconds into mm:55
var min = Math.floor(secondsRemaining / 60);
var sec = secondsRemaining - (min * 60);
//add leading 0 if seconds less than 10
if (sec < 10) {
sec = '0' + sec;
}
//concatenate with colon
var message = min.toString() + ':' + sec;
// now change the display
timeDisplay.innerHTML = message;
//stop if down to zero
if (secondsRemaining === 0) {
alert('Done!');
clearInterval(intervalHandle);
resetPage();
}
// subtract from seconds remaining
secondsRemaining--;
}
function startCountdown() {
//get contents
var minutes = document.getElementById('minutes').value;
//check if not a number
if (isNaN(minutes)) {
alert("Please enter a number!");
return;
}
//how many seconds?
secondsRemaining = minutes * 60;
//call tick
intervalHandle = setInterval(tick, 1000);
//hide form
document.getElementById('inputArea').style.display = 'none';
//show pause when running
document.getElementById("pauseArea").style.display = "block";
}
window.onload = function () {
// create text input
var inputMinutes = document.createElement('input');
inputMinutes.setAttribute('id', 'minutes');
inputMinutes.setAttribute('type', 'text');
inputMinutes.setAttribute('placeholder', 'Idő megadása');
//pause button
var pauseButton = document.getElementById("pauseBtn");
pauseButton.onclick = function() {
pauseCountdown();
};
//resume button
var resumeButton = document.getElementById("resumeBtn");
resumeButton.onclick = function() {
resumeCountdown();
};
//create button
var startButton = document.createElement('input');
startButton.setAttribute('type', 'button');
startButton.setAttribute('value', 'Indítás');
startButton.onclick = function () {
startCountdown();
};
// add to DOM
document.getElementById('inputArea').appendChild(inputMinutes);
document.getElementById('inputArea').appendChild(startButton);
document.getElementById("pauseArea").appendChild(pauseButton);
document.getElementById("resumeArea").appendChild(resumeButton);
//hide pause button by default
document.getElementById("pauseArea").style.display = "none";
//hide pause button by default
document.getElementById("resumeArea").style.display = "none";
};
Here is what i just wrote really quick. It may help you. But you can just do some basic math to get your conversions and handle the remainder. Like so:
function countDown(future_date_in_millis) {
var date = new Date();
var current_time = date.getTime();
//get the future date and time
var future_date = future_date_in_millis.getTime(); //1438077258047; //date.getTime();
// get the duration in milliseconds
// 1 day = 86400000 millis
var duration = future_date - current_time;
var dd = Math.floor(duration / 86400000);
var remainder = duration % 86400000;
var hh = Math.floor(remainder / 3600000);
remainder = remainder % 3600000;
var mm = Math.floor(remainder / 60000);
remainder = remainder % 60000;
var ss = Math.floor(remainder / 1000);
var days = document.getElementById("dd");
var hours = document.getElementById("hh");
var minutes = document.getElementById("mm");
var seconds = document.getElementById("ss");
days.innerHTML = dd.toString();
hours.innerHTML = hh.toString();
minutes.innerHTML = mm.toString();
seconds.innerHTML = ss.toString();
}
window.setInterval(function () {
/// call your function here
var d = new Date("July 15, 2015 4:52:00 PM");
countDown(d);
}, 1000);

stopwatch clear variable 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. :)

Categories