If I repeatedly click the pause and resume button on my counter, the count immediately goes up by one on every resume button press. How can i change this?
var c = 0;
var t;
function count(){
document.getElementById("count").innerHTML = c;
c = c + 1;
t = setTimeout(count, 1000);
}
function start(){
count();
document.getElementById("startb").style.display = "none";
document.getElementById("pauseb").style.display = "inline";
}
function pause(){
clearTimeout(t);
document.getElementById("startb").style.display = "inline";
document.getElementById("pauseb").style.display = "none";
document.getElementById("startb").innerHTML = "Resume";
document.getElementById("resetb").style.display = "inline";
}
function reset(){
c = 0;
clearTimeout(t);
document.getElementById("count").innerHTML = c;
document.getElementById("startb").style.display = "inline";
document.getElementById("startb").innerHTML = "Start";
document.getElementById("pauseb").style.display = "none";
document.getElementById("resetb").style.display = "none";
}
*{
margin: 0;
padding: 0;
font-family: Arial;
}
body{
background-color: #333;
color: black;
}
button{
width: 100px;
height: 30px;
line-height: 30px;
text-align: center;
color: #000;
background-color: #c3c3c3;
border: 1px solid #000;
}
#count{
font-size: 175px;
}
#pauseb {
display: none;
}
#resetb {
display: none;
}
<!DOCTYPE html>
<html>
<head>
<title>Stopwatch</title>
<script src="Stopwatch.js"></script>
<link rel="stylesheet" href="Stopwatch.css">
</head>
<body>
<h1>Stopwatch</h1>
<span id="count">0</span><br />
<button id="startb" onClick="start()">Start</button>
<button id="pauseb" onClick="pause()">Pause</button>
<button id="resetb" onClick="reset()">Reset</button>
</body>
</html>
I’m thinking an if else statement in the count function might fix this. I just can’t piece it together. Like if count doesn’t equal 0, then continue with the current count. It’s odd though to me because my resume button IS my start button, and on the very first "start" button-press, it doesn’t immediately add one second. any help is appreciated.
2
Answers
When you call the
count()
on the resume, it is adding +1 to the count, since you are calling the count function. To counter this, you could add an argument saying to not add to the value. You could also add a customresume()
function.This will allow you to start counting again without increasing the count on the
resume()
function.A little different twist here to use
c++
andc--
to increment and decrement the count.Other things: – all optional but to demonstrate some things that can make code smaller or easier or more DRY (do not repeat yourself)
show
data attribute to show and hide the elements using CSS only.body
forgrid
displaydocument.querySelector()
to target the element passing in the id prefix#
but it could be anything here16px
on the body because most browsers have that as defaultem
such as10em
which would be a160px
size to make calculations of size easier in the CSS.