Having trouble with Javascript Stopwatch - javascript

I'm working on a stopwatch, and this is my code for it. It makes perfect sense for me, but doesn't want to update for some reason.
HTML:
<ul>
<li id="hour">0</li>
<li>:</li>
<li id="min">0</li>
<li>:</li>
<li id="sec">0</li>
</ul>
JS:
var sec = document.getElementById("sec").value,
min = document.getElementById("min").value,
hour = document.getElementById("hour").value;
function stopWatch(){
sec++;
if(sec > 59) {
sec = 0;
min++;
} else if(min > 59){
min = 0;
hour++;
}
window.setTimeout("stopWatch()", 1000);
}
stopWatch();

A list item has no .value property. Inputs or textareas have. It should be
var sec = parseInt(document.getElementById("sec").innerHTML, 10),
min = parseInt(document.getElementById("min").innerHTML, 10),
hour = parseInt(document.getElementById("hour").innerHTML, 10);
which is also parsing them into numbers.
Also, don't pass a string to setTimeout. Pass the function you want to be called:
window.setTimeout(stopWatch, 1000);
And nowhere in your code you are outputting the updated variables. They are no magic pointers to the DOM properties, but just hold numbers (or strings in your original script).
Last but not least there's a logic error in your code. You are checking whether the minutes exceed 59 only when the seconds didn't. Remove that else before the if.

1) List items LI don't have values, they have innerHTML.
var sec = document.getElementById("sec").innerHTML; (not .value)
2) Nowhere in your code do you set the contents of your LIs. JavaScript doesn't magically associate IDs with variables - you have to do that bit yourself.
Such as:
document.getElementById("hour").innerHTML = hour;
3) Never pass a timeout as a string. Use an anonymous function:
window.setTimeout(function() {stopWatch()}, 1000);
or, plainly:
window.setTimeout(stopWatch, 1000);

(function() {
var sec = document.getElementById("sec").value,
min = document.getElementById("min").value,
hour = document.getElementById("hour").value;
function stopWatch(){
sec++;
if(sec > 59) {
sec = 0;
min++;
} else if(min > 59){
min = 0;
hour++;
}
document.getElementById("sec").textContent = sec
document.getElementById("min").textContent = min
document.getElementById("hour").textContent = hour
window.setTimeout(stopWatch, 1000);
}
stopWatch();
})();

The invocation should only be
window.setInterval(stopWatch, 1000);
So to use the stopwatch, put the function inside:
var sec = 0, min = 0, hour = 0;
window.setInterval(function () {
"use strict";
sec++;
if (sec > 59) {
sec = 0;
min++;
} else if (min > 59) {
min = 0;
hour++;
}
document.getElementById("sec").innerHTML = sec;
document.getElementById("min").innerHTML = hour;
document.getElementById("hour").innerHTML = hour;
}, 1000);

Li elements has no value propertie, use innerHTML.
You could store the values for sec, min & hour in variables.
It is a nice idea to store the setTimeout() call to a variable in case you want to stop the clock later. Like "pause".
http://jsfiddle.net/chepe263/A3a9m/4/
<html>
<head>
<style type="text/css">
ul li{
float: left;
list-style-type: none !important;
}
</style>
<script type="text/javascript">//<![CDATA[
window.onload=function(){
var sec = min = hour = 0;
var clock = 0;
stopWatch = function(){
clearTimeout(clock);
sec++;
if (sec >=59){
sec = 0;
min++;
}
if (min>=59){
min=0;
hour++;
}
document.getElementById("sec").innerHTML = (sec < 10) ? "0" + sec : sec;
document.getElementById("min").innerHTML = (min < 10) ? "0" + min : min;
document.getElementById("hour").innerHTML = (hour < 10) ? "0" + hour : hour;
clock = setTimeout("stopWatch()",1000); }
stopWatch();
pause = function(){
clearTimeout(clock);
return false;
}
play = function(){
stopWatch();
return false;
}
reset = function(){
sec = min = hour = 0;
stopWatch();
return false;
}
}//]]>
</script>
</head>
<body>
<ul>
<li id="hour">00</li>
<li>:</li>
<li id="min">00</li>
<li>:</li>
<li id="sec">49</li>
</ul>
<hr />
Pause
Continue
Reset
</body>
</html>

This is my complete code, this may help you out:
<html>
<head>
<title>Stopwatch Application ( Using JAVASCRIPT + HTML + CSS )</title>
<script language="JavaScript" type="text/javascript">
var theResult = "";
window.onload=function() { document.getElementById('morefeature').style.display = 'none'; }
function stopwatch(text) {
var d = new Date(); var h = d.getHours(); var m = d.getMinutes(); var s = d.getSeconds(); var ms = d.getMilliseconds();
document.stopwatchclock.stpwtch.value = + h + " : " + m + " : " + s + " : " + ms;
if (text == "Start") {
document.stopwatchclock.theButton.value = "Stop";
document.stopwatchclock.theButton.title = "The 'STOP' button will save the current stopwatch time in the stopwatch history, halt the stopwatch, and export the history as JSON object. A stopped stpwatch cannot be started again.";
document.getElementById('morefeature').style.display = 'block';
}
if (text == "Stop") {
var jsnResult = arrAdd();
var cnt = 0; var op= 'jeson output';
for (var i = 0; i < jsnResult.length; i++) {
if (arr[i] !== undefined) {
++cnt; /*json process*/
var j={ Record : cnt, Time : arr[i]};
var dq='"';
var json="{";
var last=Object.keys(j).length;
var count=0;
for(x in j){ json += dq+x+dq+":"+dq+j[x]+dq; count++;
if(count<last)json +=",";
}
json+="}<br>";
document.write(json);
}
}
}
if (document.stopwatchclock.theButton.value == "Start") { return true; }
SD=window.setTimeout("stopwatch();", 100);
theResult = document.stopwatchclock.stpwtch.value;
document.stopwatchclock.stpwtch.title = "Start with current time with the format (hours:mins:secs.milliseconds)" ;
}
function resetIt() {
if (document.stopwatchclock.theButton.value == "Stop") { document.stopwatchclock.theButton.value = "Start"; }
window.clearTimeout(SD);
}
function saveIt() {
var value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value; value++;
document.getElementById('number').value = value;
var resultTitle = '';
if(value == '1'){ resultTitle = "<h3>History</h3><hr color='black'>"; }
var objTo = document.getElementById('stopwatchresult')
var spanTag = document.createElement("span");
spanTag.id = "span"+value;
spanTag.className ="stopWatchClass";
spanTag.title ="The stopwatch showing current stopwatch time and a history of saved times. Each saved time are shown as total duration (split time - stopwatch start time) and a lap duration (split time - previous split time). And durations are shown in this format: 'hours:mins:secs.milliseconds'";
spanTag.innerHTML = resultTitle +"<br/><b>Record " + value+" =</b> " + theResult + "";
objTo.appendChild(spanTag);
arrAdd(theResult);
return;
}
var arr = Array();
function arrAdd(value){ arr.push(value); return arr;}
</script>
<style>
center {
width: 50%;
margin-left: 25%;
}
.mainblock {
background-color: #07c1cc;
}
.stopWatchClass {
background-color: #07c1cc;
display: block;
}
#stopwatchclock input {
margin-bottom: 10px;
width: 120px;
}
</style>
</head>
<body>
<center>
<div class="mainblock">
<h1><b title="Stopwatch Application ( Using JAVASCRIPT + HTML + CSS )">Stopwatch Application</b></h1>
<form name="stopwatchclock" id="stopwatchclock">
<input type="text" size="16" class="" name="stpwtch" value=" 00 : 00 : 00 : 00" title="Initially blank" />
<input type="button" name="theButton" id="start" onClick="stopwatch(this.value);" value="Start" title="The 'START' button is start the stopwatch. An already started stopwatch cannot be started again." /><br />
<div id="morefeature">
<input type="button" value="Reset" id="resetme" onClick="resetIt();reset();" title="Once you will click on 'RESET' button will entirely reset the stopwatch so that it can be started again." />
<input type="button" name="saver" id="split" value="SPLIT" onClick="saveIt();" title="The 'SPLIT' button will save the current stopwatch time in the stopwatch history. The stopwatch will continue to progress after split." />
<div>
<input type="hidden" name="number" id="number" value="0" />
</form>
</div>
<div id="stopwatchresult"></div>
</center>
</body>

Related

Add value from textbox to counter

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

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>

Can't get form to hide in JS

Having this problem with trying to get a form to hide in Javascript.
Here is my HTML:
<!DOCTYPE html>
<html>
<head>
<title>Timer</title>
<link rel="stylesheet" href="style.css">
<script src="javascript.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<link href='https://fonts.googleapis.com/css?family=Roboto:400,300' rel='stylesheet' type='text/css'>
</head>
<body>
<div id="wrapper">
<div id="time">00:00:00</div>
<form id="myform">
<input type="text" autocomplete="off" id="box" placeholder="00:00:00" onkeypress="checkBox(event)">
</form>
</div>
</body>
</html>
And here is my JS:
function timer(time) {
document.getElementById("myform").style.display = "none";
document.getElementById("time").style.display = "inline";
var interval = setInterval(function () {
if (time == 0) {
time = 299;
} else {
var newTime = timeFormat(time);
document.getElementById("time").innerHTML = newTime;
document.title = newTime;
time--;
}
}, 1000);
}
function checkBox(event) {
if (event.keyCode == 13) {
var string = document.getElementById("box").value;
var numTest = string;
if (string.length != 0) {
var numOfColons = string.split(":").length - 1;
var hr = 0;
var min = 0;
var sec = 0;
if (numOfColons == 2) {
numTest = numTest.replace(":", "");
numTest = numTest.replace(":", "");
hr = string.substring(0, string.indexOf(":"));
string = string.replace(string.substring(0, string.indexOf(":")+1), "");
min = string.substring(0, string.indexOf(":"));
string = string.replace(string.substring(0, string.indexOf(":")+1), "");
sec = string.substring(0, string.length);
} else if (numOfColons == 1) {
numTest = numTest.replace(":", "");
min = string.substring(0, string.indexOf(":"));
string = string.replace(string.substring(0, string.indexOf(":")+1), "");
sec = string.substring(0, string.length);
} else if (numOfColons == 0) {
sec = string;
}
hr = parseInt(hr);
min = parseInt(min);
sec = parseInt(sec);
if(/^\d+$/.test(numTest)) {
var totalSec = hr*3600 + min*60 + sec;
if (totalSec > 0) {
timer(totalSec);
}
}
}
}
}
function focus() {
document.getElementById("box").focus();
}
function timeFormat(time) {
var sec = time % 60;
var totalMin = time / 60;
var min = Math.floor(totalMin % 60);
var string = "";
if (min == 0 && sec < 10) {
string = "0:0" + sec;
} else if (min == 0) {
string = "0:" + sec;
} else if (sec < 10) {
string = min + ":0" + sec;
} else {
string = min + ":" + sec;
}
return string;
}
Note that I am not using a button to trigger the form submission, I am simply using a onkeypress event to detect if the user hit the enter button (I wanted a cleaner design). Whenever the timer function is called, the text box flickers like it turns off for a second, than it comes back on in an instant. I have no idea what the problem is. I also have gotten no errors in console.
Am not sure what you are trying to achieve but from looking at your code, Hitting enter results in the page being reloaded, so I can't get to see the result.
I would however suggest you use jQuery to hide show your results, since you are already calling the script
$('#myform').hide();
$('#time').show();
The problem is this line of code. It turns the form off for a split second, which causes the blinking effect to occur. Simply remove this or comment it out.
document.getElementById("myform").style.display = "none";
If you want to hide the form, use jQuery's $('#myForm').hide() function. It's similar to <form id="myform" style="display:none;">
You could also try this:
<input type="text" id="timeInputBox" autocomplete="off" id="box" placeholder="00:00:00" onkeypress="checkBox(event)">
With this:
document.getElementById('timeInputBox').style.display = "none"; // JS
Or use this:
$('#timeInputBox').hide(); // jQuery
You may also want to move the jQuery <script> tag up higher in your <head> block. It needs to go before your call to your external <script src="javascript.js"></script> tag. Then you can use the $ and all of these functions from api.jquery.com in your .js file.

JS function stopwatch application confuses the user

I wrote a javascript application but I end up with a total confusion. This js application needs to run in minutes, seconds, and hundredths of seconds. The part about this mess is when the stopwatch show, in this case 03:196:03. Here is my confusion. When the stopwatch shows 196, is it showing hundredth of seconds? Does anybody can check my function and tell me what part needs to be corrected in case that the function is wrong?
<html>
<head>
<title>my example</title>
<script type="text/javascript">
//Stopwatch
var time = 0;
var started;
var run = 0;
function startWatch() {
if (run == 0) {
run = 1;
timeIncrement();
document.getElementById("countDown").disabled = true;
document.getElementById("resetCountDown").disabled = true;
document.getElementById("start").innerHTML = "Stop";
} else {
run = 0;
document.getElementById("start").innerHTML = "Resume";
}
}//End function startWatch
function watchReset() {
run = 0;
time = 0;
document.getElementById("start").innerHTML = "Start";
document.getElementById("output").innerHTML = "00:00:00";
document.getElementById("countDown").disabled = false;
document.getElementById("resetCountDown").disabled = false;
}//End function watchReset
function timeIncrement() {
if (run == 1) {
setTimeout(function () {
time++;
var min = Math.floor(time/10/60);
var sec = Math.floor(time/10);
var tenth = time % 10;
if (min < 10) {
min = "0" + min;
}
if (sec <10) {
sec = "0" + sec;
} else if (sec>59) {
var sec;
}
document.getElementById("output").innerHTML = min + ":" + sec + ":0" + tenth;
timeIncrement();
},10);
}
} // end function timeIncrem
function formatNumber(n){
return n > 9 ? "" + n: "0" + n;
}
</script>
</head>
<body>
<h1>Stopwatch</h1>
<p id="output"></p>
<div id="controls">
<button type="button" id ="start" onclick="startWatch();">Start</button>
<button type="button" id ="reset" onclick="watchReset();">Reset</button>
</div>
</body>
</html>
Your code is totally weird!
First you're using document.getElementById() for non-existing elements: maybe they belong to your original code and your didn't posted it complete.
Then I don't understand your time-count method:
you make timeIncrement() to be launched every 10 ms: so time/10 gives you a number of milliseconds
but you compute min and sec as if it was a number of seconds!
From there, all is wrong...
Anyway IMO your could make all that simpler using the getMilliseconds() function of the Date object.
Try this:
document.getElementById("output").innerHTML = [
Math.floor(time/100/60 % 60),
Math.floor(time/100 % 60),
time % 100
].map(formatNumber).join(':')
var time = 0;
var started;
var run = 0;
function startWatch() {
if (run == 0) {
run = 1;
timeIncrement();
} else {
run = 0;
}
}
function watchReset() {
run = 0;
time = 0;
document.getElementById("output").innerHTML = "00:00:00";
}
function timeIncrement() {
if (run == 1) {
setTimeout(function () {
time++;
document.getElementById("output").innerHTML = [
Math.floor(time/100/60 % 60),
Math.floor(time/100 % 60),
time % 100
].map(formatNumber).join(':')
timeIncrement();
},10);
}
}
function formatNumber(n){
return (n < 10 ? "0" : "") + n;
}
startWatch()
<div id="output"></div>

Blinking image issues for javascript timer

I am having an issue with the timer I created. I just added in a code snippet that will cause a red rectangle to begin flashing(blinking) on the screen between 30 seconds and zero seconds. Once the timer hits zero the blinking needs to stop. The timer should only blink between 30 seconds and 0 seconds. For some reason my blinkRed() function is going haywire and I cannot figure out why. Sometimes it stops when it is supposed to other times it does whatever.
My code is below:
var seconds = 20; //Variables for the code below
var countdownTimer;
var imgBlink;
function showGreen() {
var imgGreen = document.getElementById('greenGo');
imgGreen.style.visibility = 'visible';
};
function hideGreen() {
var imgGreen = document.getElementById('greenGo');
imgGreen.style.visibility = 'hidden';
};
function showYellow() {
var imgYellow = document.getElementById('yellowAlmost');
imgYellow.style.visibility = 'visible';
};
function hideYellow() {
var imgYellow = document.getElementById('yellowAlmost');
imgYellow.style.visibility = 'hidden';
};
function blinkRed(){
var redBlink = document.getElementById('redStop');
if(redBlink.style.visibility == 'hidden'){
redBlink.style.visibility = 'visible';
} else {
redBlink.style.visibility = 'hidden';
}
imgBlink = setTimeout("blinkRed()", 1000);
};
function showRed() {
var imgRed = document.getElementById('redStop');
imgRed.style.visibility = 'visible';
};
function hideRed() {
var imgRed = document.getElementById('redStop');
imgRed.style.visibility = 'hidden';
};
function secondPassed(){
var minutes = Math.floor(seconds/60); //takes the output of seconds/60 and makes rounds it down. 4.7 = 4, 3.7 = 3. (to keep the minutes displaying right)
var remainingSeconds = seconds % 60; //takes remainder of seconds/60 and displays it. so 270/60 = 4.5 this displays it as 30 so it becomes 4:30 instead of 4.5
if (remainingSeconds < 10) { //if remaining seconds are less than 10 add a zero before the number. Displays numbers like 09 08 07 06
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds; //displays time in the html page 5:06
document.getElementById('countdown2').innerHTML = minutes + ":" + remainingSeconds; //displays the time a second time
if (seconds == 0) {
clearInterval(countdownTimer);//keeps value at zero once it hits zero. 0:00 will not go anymore
alert("Time is Up, Try again");
}
};
function changeColor(){ //this changes the background color based on the time that has elapsed
if (seconds <= 300 && seconds > 150) { //green between 5:00 - 1:30
//document.body.style.background = "url("+colorChange[0]+")";
showGreen();
}
else if (seconds <= 150 && seconds > 60) { //yellow between 1:30 - 30
//document.body.style.background = "url("+colorChange[1]+")";
hideGreen();
showYellow();
}
else if(seconds <= 60 && seconds > 30){ // red between 30 - 0
//document.body.style.background = "url("+colorChange[2]+")";
hideYellow();
showRed();
}
else if (seconds <= 30 && seconds > 0) {
hideRed();
blinkRed();
}
else if (seconds == 0){
clearTimeout(imgBlink);
}
};
function countdown(start){ //code for the button. When button is clicked countdown() calls on secondPassed() to begin count down.
secondPassed();
if (seconds != 0) { //actual code to decrement the time
seconds --;
countdownTimer = setTimeout('countdown()', 1000);
changeColor(); //calls the changeColor() function so that background changes
start.disabled = true; //disables the "start" button after being pressed
}
if (start.disabled = true){ //if one of the 'start' buttons are pressed both are disabled
start2.disabled = true;
}
//startDisabled2();
};
function cdpause() { //pauses countdown
// pauses countdown
clearTimeout(countdownTimer);
clearTimeout(imgBlink);
};
function cdreset() {
// resets countdown
cdpause(); //calls on the pause function to prevent from automatically starting after reset
secondPassed(); //reverts back to original secondPassed() function
document.getElementById('start').disabled = false; //Enables the "start" button that has been disabled from countdown(start) function.
document.getElementById('start2').disabled = false; //enables the 'start2' button. same as above.
hideGreen();
hideYellow();
hideRed();
};
#countdown{
font-size: 2em;
position: inherit;
left: 120px;
top: 5px;
}
#countdown2{
font-size: 2em;
position: inherit;
left: 120px;
top: 30px;
}
#greenGo{
visibility: hidden;
position: absolute;
bottom: 20px;
z-index: -1;
}
#yellowAlmost{
visibility: hidden;
position: absolute;
bottom: 20px;
z-index: -1;
}
#redStop {
visibility: hidden;
position: absolute;
bottom: 20px;
z-index: -1;
}
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="newTicket2.0.css">
<script src = "Timer2.js">
</script>
</head>
<<div id = "timerBackground">
<span id="countdown" class="timer"></span>
<div id = "timerButtons">
<input type="button" value="Start" onclick="countdown(this)" id = "start">
<input type="button" value="Stop" onclick="cdpause()">
<input type="button" value="Reset" onclick="cdreset(seconds = 300)">
</div>
</div>
<div id = "timerBackground2">
<span id="countdown2" class="timer"></span>
<div id = "timerButtons2">
<input type="button" value="Start" onclick="countdown(this)" id = "start2">
<input type="button" value="Stop" onclick="cdpause()">
<input type="button" value="Reset" onclick="cdreset(seconds = 300)">
</div>
</div>
<img src = "greenGo.png" id = "greenGo" alt = "greenGo">
<img src = "redStop.png" id = "redStop" alt = "redStop">
<img src = "yellowAlmost.png" id = "yellowAlmost" alt = "yellowAlmost">
</body>
</html>
Ive attempted to add clearTimeout(imgBlink); to just about everything I can think of and nothing seems to work. It just keeps ticking away.
Just figured it out. I added:
imgBlink = setTimeout("blinkRed()", 1000);
if(seconds == 0){
clearTimeout(imgBlink);
}
Into the blinkRed() function and now it works like a charm. Although if you press the stop button twice it continues to tick. But that is a minor issue.
Here is the updated javascript.
var seconds = 20; //Variables for the code below
var countdownTimer;
var imgBlink;
/*function startDisabled2() {
start2.disabled == true;
if (start2.disabled == true) {
start.disabled = true;
}
};*/
function showGreen() {
var imgGreen = document.getElementById('greenGo');
imgGreen.style.visibility = 'visible';
};
function hideGreen() {
var imgGreen = document.getElementById('greenGo');
imgGreen.style.visibility = 'hidden';
};
function showYellow() {
var imgYellow = document.getElementById('yellowAlmost');
imgYellow.style.visibility = 'visible';
};
function hideYellow() {
var imgYellow = document.getElementById('yellowAlmost');
imgYellow.style.visibility = 'hidden';
};
function showRed() {
var imgRed = document.getElementById('redStop');
imgRed.style.visibility = 'visible';
};
function hideRed() {
var imgRed = document.getElementById('redStop');
imgRed.style.visibility = 'hidden';
};
function blinkRed(){
var redBlink = document.getElementById('redStop');
if(redBlink.style.visibility == 'hidden'){
redBlink.style.visibility = 'visible';
} else {
redBlink.style.visibility = 'hidden';
}
imgBlink = setTimeout("blinkRed()", 1000);
if(seconds == 0){
clearTimeout(imgBlink);
}
};
/*function stopBlinkRed() {
clearInterval(imgBlink);
};*/
function secondPassed(){
var minutes = Math.floor(seconds/60); //takes the output of seconds/60 and makes rounds it down. 4.7 = 4, 3.7 = 3. (to keep the minutes displaying right)
var remainingSeconds = seconds % 60; //takes remainder of seconds/60 and displays it. so 270/60 = 4.5 this displays it as 30 so it becomes 4:30 instead of 4.5
if (remainingSeconds < 10) { //if remaining seconds are less than 10 add a zero before the number. Displays numbers like 09 08 07 06
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds; //displays time in the html page 5:06
document.getElementById('countdown2').innerHTML = minutes + ":" + remainingSeconds; //displays the time a second time
if (seconds == 0) {
clearInterval(countdownTimer);//keeps value at zero once it hits zero. 0:00 will not go anymore
alert("Time is Up, Try again");
}
};
function changeColor(){ //this changes the background color based on the time that has elapsed
if (seconds <= 300 && seconds > 150) { //green between 5:00 - 1:30
//document.body.style.background = "url("+colorChange[0]+")";
showGreen();
}
else if (seconds <= 150 && seconds > 60) { //yellow between 1:30 - 30
//document.body.style.background = "url("+colorChange[1]+")";
hideGreen();
showYellow();
}
else if(seconds <= 60 && seconds > 30){ // red between 30 - 0
//document.body.style.background = "url("+colorChange[2]+")";
hideYellow();
showRed();
}
else if (seconds <= 30 && seconds > 0) {
hideRed();
blinkRed();
}
else if (seconds == 0){
showRed();
}
};
function countdown(start){ //code for the button. When button is clicked countdown() calls on secondPassed() to begin count down.
secondPassed();
if (seconds != 0) { //actual code to decrement the time
seconds --;
countdownTimer = setTimeout('countdown()', 1000);
changeColor(); //calls the changeColor() function so that background changes
start.disabled = true; //disables the "start" button after being pressed
}
if (start.disabled = true){ //if one of the 'start' buttons are pressed both are disabled
start2.disabled = true;
}
//startDisabled2();
};
function cdpause() { //pauses countdown
// pauses countdown
clearTimeout(countdownTimer);
clearTimeout(imgBlink);
};
function cdreset() {
// resets countdown
cdpause(); //calls on the pause function to prevent from automatically starting after reset
secondPassed(); //reverts back to original secondPassed() function
document.getElementById('start').disabled = false; //Enables the "start" button that has been disabled from countdown(start) function.
document.getElementById('start2').disabled = false; //enables the 'start2' button. same as above.
hideGreen();
hideYellow();
hideRed();
};

Categories