I'm making a timer that records the longest time (personal best) when clicking 'ok' on the pass button. I can't seem to figure out how to get the counter back to 0 and I'm sure there's a way to do it with only 2 buttons (start + pass). I want the timer to start again when I press start, at the moment it just runs each case once and returns the highest value. The timer currently logs the second after the number shown on screen which I do not understand.
Thanks in advance for your help, much appreciated!
var c = 0;
var d = 0;
var pb;
function myCounter() {
document.getElementById("demo").innerHTML = c++;
}
function restartCount() {
document.getElementById("demo").innerHTML = d++;
}
function userPass() {
if (confirm("Are you sure?")) {
console.log(c,d);
clearInterval(myCounter);
clearInterval(restartCount);
document.getElementById("personalBest").innerHTML = Math.max(c,d);
} else {
document.getElementById("good").innerHTML = "Keep it up!";
}
}
<h1>Best Time = <span id="personalBest"></span></h1>
<p id="good"></p>
<p id="demo"></p>
<button onClick="myCounter = setInterval(myCounter, 1000)">Start counter!</button>
<button onclick="userPass()">Pass</button>
<button onclick="restartCount = setInterval(restartCount, 1000)">Restart</button>
Regarding your second question "The timer currently logs the second after the number shown on screen which I do not understand."
This is linked to where you put the ++ in this line
document.getElementById("demo").innerHTML = c++;
c++ means get the value of c then increment it. I believe you want to increment first (because 1 second has elapse) then assign and use.
In this case you should use ++c instead.
document.getElementById("demo").innerHTML = ++c;
There were a few mistakes
timer variable name and function variable name were same, they need to be different. Also, it is cleaner to invoke a simple method rather than starting timer from the onclick.
No need for second start button, ensure that you clear c and timer before starting new timer.
var c = 0;
var d = 0;
var myCounter;
function myCounter1() {
c = 0; //set c to 0;
clearInterval(myCounter);
myCounter = setInterval(() => {
document.getElementById("demo").innerHTML = c++;
}, 1000);
}
function userPass() {
if (confirm("Are you sure?")) {
d = Math.max(c,d);
clearInterval(myCounter);
document.getElementById("personalBest").innerHTML = d;
} else {
document.getElementById("good").innerHTML = "Keep it up!";
}
}
<h1>Best Time = <span id="personalBest"></span></h1>
<p id="good"></p>
<p id="demo"></p>
<button onClick="myCounter1()">Start counter!</button>
<button onclick="userPass()">Pass</button>
Related
This question already has an answer here:
JavaScript countdown timer with on key press to reset the timer
(1 answer)
Closed 11 months ago.
I have a simple HTML stopwatch logic where I can start and stop the clock with the button click. By clicking on the start button, one can start the timer (shows current time) and update every second. One can stop it by clicking stop button. But if one clicks on start button twice, there is nothing I can do to stop the timer. Below is my code:
var hour = document.getElementById("hoursOut");
var minute = document.getElementById("minsOut");
var second = document.getElementById("secsOut");
var btnStart = document.getElementById("btnStart");
var btnStop = document.getElementById("btnStop");
var waitTimer;
function displayTime() {
var currentTime = new Date();
var currentHour = currentTime.getHours();
var currentMinute = currentTime.getMinutes();
var currentSeconds = currentTime.getSeconds();
hour.innerHTML = twoDigit(currentHour) + ":";
minute.innerHTML = twoDigit(currentMinute) + ":";
second.innerHTML = twoDigit(currentSeconds);
}
function twoDigit(digit) {
if (digit < 10) {
digit = "0" + digit;
}
return digit;
}
function startClock() {
waitTimer = setInterval(displayTime, 1000);
}
function stopClock() {
clearInterval(waitTimer);
}
btnStart.onclick = startClock;
btnStop.onclick = stopClock;
<h1>JavaScript Clock</h1>
<div id="calendarBox">
<!-- OUTPUT TIME VALUES -->
<p class="timeDisplay">
<span id="hoursOut">00:</span>
<span id="minsOut">00:</span>
<span id="secsOut">00</span>
</p>
<!-- BUTTON SET -->
<input id="btnStart" type="button" value="START" />
<input id="btnStop" type="button" value="STOP" />
</div>
I have checked some answers in stackoverflow but most solutions uses a for-loop from 0 to 1000 until it finds the interval id and stop all of them using loop. I am confident there should be an elegant solution than that.
// some stackoverflow suggested answer
for (var i = 1; i < 99999; i++)
window.clearInterval(i);
A possible solution is to prevent the problem before it happens. You can place a check on the running timer (Is there a way to check if a var is using setInterval()?).
In this case you could just have a global timer variable var timer = false the with add a check to the start function. Then the stop function will set the timer variable back to false.
function startClock() {
if(!timer){
timer = true
waitTimer = setInterval(displayTime, 1000);
}
else return
}
function stopClock() {
clearInterval(waitTimer);
timer = false
}
when you double click you start a new setInterval(). So you now have two set intervals running. Only problem is you can't access the first one cause you named the second one the same name. Check if waitTimer exists and if it does stop it. see code:
UPDATE: actually you don't even need an if statement. just call stopClock() before you set waitTimer -- code snippet adjusted
var hour = document.getElementById("hoursOut");
var minute = document.getElementById("minsOut");
var second = document.getElementById("secsOut");
var btnStart = document.getElementById("btnStart");
var btnStop = document.getElementById("btnStop");
var waitTimer;
function displayTime() {
var currentTime = new Date();
var currentHour = currentTime.getHours();
var currentMinute = currentTime.getMinutes();
var currentSeconds = currentTime.getSeconds();
hour.innerHTML = twoDigit(currentHour) + ":";
minute.innerHTML = twoDigit(currentMinute) + ":";
second.innerHTML = twoDigit(currentSeconds);
}
function twoDigit(digit) {
if (digit < 10) {
digit = "0" + digit;
}
return digit;
}
function startClock() {
stopClock();
waitTimer = setInterval(displayTime, 1000);
}
function stopClock() {
clearInterval(waitTimer);
}
btnStart.onclick = startClock;
btnStop.onclick = stopClock;
<h1>JavaScript Clock</h1>
<div id="calendarBox">
<!-- OUTPUT TIME VALUES -->
<p class="timeDisplay">
<span id="hoursOut">00:</span>
<span id="minsOut">00:</span>
<span id="secsOut">00</span>
</p>
<!-- BUTTON SET -->
<input id="btnStart" type="button" value="START" />
<input id="btnStop" type="button" value="STOP" />
</div>
Please i want to change the temperature level in each button click. In a way to have a white arrow in a first time, two white arrow i a seconde time .... i have images withe 1 arrow, 2 arrow ext.
this my image in html :
<div id="WBR"><img src="assets/AWImages/V0.png"></div>
<button id= "HI" class="circle" >+</button>
I simulate the button click in javascript like this :
let addb = document.querySelector('#HI');
addb.addEventListener('click', () =>{
input.value = parseInt(input.value)+1;
if((input.value)<5)
{
socket.emit('Value of hum changed',input.value);
}
else
{
input.value =4;
}
});
I really appreciate ur help ;)
let addb = document.querySelector('#WBR');
let wbr = document.querySelector('#HI');
var f = document.querySelector('#f');
var Score = 0;
var win = 5;
var gameOver = false;
addb.addEventListener("click", function () {
if (!gameOver) {
Score++ ;
if (Score == win) {
gameOver = true;
addb.style.color = "green";
}
f.innerHTML = Score;
}
});
<div id="WBR"><img src="assets/AWImages/V0.png"></div>
<button id= "HI" class="circle" >+</button>
<p id="f">0</p>
I'm trying to make a dice game where the goal for each of participants is to collect points as fast as possible to pass 100. Each participant can throw the die as many times as they want and add the points, but achieved points within a certain game fall away if a one is rolled. For example, if you have 15 points in a game and have stopped in time, these points can be taken further to round two. These points cannot be lost in a later round and thus become included in the summary.
I've managed to:
write the code that shows images of dice and sums up the current score (images = 1.png, 2.png etc).
Resets the current score to 0 when the player rolls a one.
What I need help with is how to write the code that activates the button "done for now" and takes that value and pushes it into an array(????) then clears the score for the next round -> then displaying the score on the site while the other rounds keep on going. It should also sum up the score and throws from each round (first to 100).
Here is my code:
var points = 0;
var start, dice, print;
window.onload = run;
function $(id) {
return document.getElementById(id);
}
function run() {
start = $("throwDice");
dice = $("dice");
print = $("print");
start.onclick = throwDice;
}
function throwDice() {
var throwD = Math.floor(Math.random() * 6) + 1;
throwD.innerHTML = '<img width="20%" src="' + throwD + '.jpg">';
add(throwD);
}
function add(value) {
points += value;
if (value == 1) {
points = 0;
$("print2").innerHTML = "GAME OVER"
} else {
$("print2").innerHTML = "";
$("print").innerHTML = points;
}
}
<div class="round">
<h1>The endless road</h1>
<button id="throwDice">Throw Dice</button> <button>Done for now</button>
<div id="dice" class="dice"></div>
<h2 id="print"></h2>
<p id="print2"></p>
</div>
Basically you just have to add another click event listener to the 'Done for now' button whose callback function
pushes the current points to an array
resets the points to 0
updates the text elements on screen
Something like:
var points = 0;
var pointsArray = new Array();
var start, dice, print;
function $(id) {
return document.getElementById(id);
}
function run() {
start = $("throwDice");
dice = $("dice");
print = $("print");
start.onclick = throwDice;
done = $("done");
done.onclick = stopRound;
}
function stopRound() {
pointsArray.push(points);
points = 0;
$("print").innerHTML = points;
$("print3").innerHTML = pointsArray;
}
function throwDice() {
var throwD = Math.floor(Math.random() * 6) + 1;
throwD.innerHTML = '<img width="20%" src="' + throwD + '.jpg">';
add(throwD);
}
function add(value) {
points += value;
if (value == 1) {
points = 0;
$("print2").innerHTML = "GAME OVER"
} else {
$("print2").innerHTML = "";
$("print").innerHTML = points;
}
}
run();
<div class="round">
<h1>The endless road</h1>
<button id="throwDice">Throw Dice</button> <button id="done">Done for now</button>
<div id="dice" class="dice"></div>
<p id="print3" style="float:right;"></p>
<h2 id="print"></h2>
<p id="print2"></p>
</div>
Sorry for my English.
A want to write out numbers (0, 3, 6, 9... 27) with the help of a for loop, but it seems it is harder than I thought. Thank You for your help.
I found a similar problem: For loop onclick button
function count() {
var i = 0;
if (i < 10) {
document.getElementById("demo").innerHTML = (i * 3);
} else {
document.getElementById("demo").innerHTML = "nothing";
}
i++;
}
<div>
<h1>This is a Heading</h1>
<h1 onclick="count()"><span>Click on me</span></h1>
<br/>
<p id="demo"></p>
</div>
View on JSFiddle
If I understand correctly, I don't think you need a for loop.
Your current code defines i=0 each time the function is called.
You'll just need to define the i variable outside of your function so it can be properly incremented.
var i = 0;
function count() {
if (i < 10) {
document.getElementById("demo").innerHTML = (i * 3);
} else {
document.getElementById("demo").innerHTML = "nothing";
}
i++;
}
<div>
<h1>This is a Heading</h1>
<h1 onclick="count()"><span>Click on me</span></h1>
<br/>
<p id="demo"></p>
</div>
Alternatively, increment the counter by three upon each click. Below, I'm using the ternary operator. It's saying, "if i is less than 27, add three. otherwise, set it to 'nothing'."
var i = 0,
output = document.getElementById('output');
function increment() {
i = i < 27 ? i + 3 : 'nothing';
output.innerHTML = i;
}
document.getElementById('trigger').addEventListener('click', increment);
<h1 id="trigger">Click on me</h1>
<p id="output">0</p>
How about something like that:
function count() {
for (i=0; i<10; i++) {
document.getElementById("demo").innerHTML += (i * 3)
}
}
I have a timer for my game, but the message will keep going on the mage, so it says it multiple times, i was wondering how you can get it to say it once.
<head>
<script type="text/javascript">
var c=10;
var t;
var timer_is_on=0;
function timedCount() {
document.getElementById('txt').value = c;
c = c - 1;
if (c == -1||c < -1){
var _message = document.createTextNode("You have mined 1 iron ore!");
document.getElementById('message').appendChild(_message);
startover();
}
}
function startover() {
c = 10;
clearTimeout(t);
timer_is_on=0;
doMining();
}
function doMining() {
if (!timer_is_on) {
timer_is_on = true;
t = setInterval(function () {
timedCount();
}, 1000);
}
}
</script>
<SPAN STYLE="float:left">
<form>
<input type="button" value="Mining" onClick="doMining()">
<input type="text" id="txt">
</form>
</SPAN>
<html>
<center>
<div id='message'></div>
Instead of setInterval use window.setTimeout.
This will trigger the function only once.
Edit: if you mean you want one message to appear and update every time, first add global counter:
var mineCount = 0;
Then change the code to this:
if (c <= -1) {
mineCount++;
var _message = "You have mined " + mineCount + " iron ore" + ((mineCount > 1) ? "s" : "") + "!";
document.getElementById('message').innerHTML = _message;
startover();
}
This will assign the contents of the element instead of adding to it each time.
Your startOver function calls doMining(). Surely, it shouldn't...?