Creating a stopwatch which counts down, Initial value from input box - javascript

I seem to only advance one digit upon button click and then it stops because the countdown is reverting to the initial value from the input box. I want an initial value entered into the input field, then used as the starting time for the countdown, which will continue until 0.
I'm quite stuck. Is there a solution?
function startButton() {
//--inputValue
var d = document.getElementById("inputValue").value;
if (d != 0) {
--d;
document.getElementById("demo").innerHTML = d;
document.getElementById("omed").innerHTML = "Thank you";
}
else
{
document.getElementById("omed").innerHTML = "Please enter your time";
}
}
<p>Stopwatch </p>
<input type = "number" id = "inputValue"> minutes</input>
<br><br>
<button onClick= "setInterval(startButton(), 1000)">Start counter!
</button>
<button onClick="clearInterval(myTimer)">Pause counter!
</button>
<p id = "demo"></p>
<br>
<p id = "omed">Enter countdown length</p>

What you want to do is to set a variable that contains a timer.
var myTimer = setInterval(function() { /* your action */ }, 60000 );
This will set a timer that fires every 1 minute the "your action" part. As you're using a variable you know how to access the timer and can stop/start it whenever you want.
Now in there we can put your code to update the HTML-element as:
document.getElementById("demo").innerHTML = --d;
The code will be:
var myTimer = setInterval(function() {
document.getElementById("demo").innerHTML = --d;
}, 60000);
You can now stop the timer by calling: clearInterval(myTimer) anywhere you want. So you can still use that in your onClick.
The problem in the above example is that now it will count down even when it hits 0. So you want to stop it automatically as soon as it hits 0.
This can be done by checking on the variable:
if (d !== 0) {
document.getElementById("demo").innerHTML = --d;
}else {
clearInterval(myTimer); // clear the timer when it hits 0 to make sure it'll not go under 0
}
I have added some feedback in the code as well. But it's easy to read: If it's more then 0 then do: d - 1. If it's 0 then stop the timer. You could also put in the else { } a message that the timer is finished.
I changed a few things with the above information in your code:
var myTimer = null;
function startButton() {
clearInterval(myTimer); // Clear the interval so it restarts when reclicking
var d = document.getElementById("inputValue").value;
if (d !== 0) {
document.getElementById("demo").innerHTML = d; // Set info ready so user knows countdown started.
myTimer = setInterval(function() {
if (d !== 0) {
document.getElementById("demo").innerHTML = --d;
}else {
clearInterval(myTimer); // clear the timer when it hits 0 to make sure it'll not go under 0
}
}, 60000);
}
else
{
document.getElementById("omed").innerHTML = "Please enter your time";
myTimer.clearInterval();
}
}
<p>Stopwatch</p>
<input type="number" id="inputValue"> minutes </input>
<br><br>
<button onClick="startButton()">Start counter!
</button>
<button onClick="clearInterval(myTimer)">Pause counter!
</button>
<p id = "demo"></p>
<br>
<p id = "omed">Enter countdown length</p>
Tip: For testing purpose it could be easier to use seconds (1000 instead of 60000) in the interval.

I have modified your code. It seems what you are looking for.
var d = 0;
function setTime(){
d = document.getElementById("inputValue").value;
}
function stopwatch() {
d--;
document.getElementById("demo").innerHTML = d;
document.getElementById("omed").innerHTML = "Thank you";
startButton()
}
var myTimer;
function startButton() {
if (d != 0) {
myTimer = setTimeout(stopwatch, 1000);
}
else
{
document.getElementById("inputValue").value="";
document.getElementById("omed").innerHTML = "Please enter your time";
}
}
<input type = "number" id = "inputValue" onchange="setTime()"> minutes</input>
<br><br>
<button onClick= "startButton()">Start counter!
</button>
<button onClick="clearInterval(myTimer)">Pause counter!
</button>
<p id = "demo"></p>
<br>
<p id = "omed">Enter countdown length</p>

Related

Set a 10-second timer for each subject input

I've been making a typing game at school. The time setting does not work.
A time limit of 10 seconds is attached to each subject. When one subject is finished, the time will be reset to 10 seconds again.Please give me some advice.
1,The user sees the subject text, types the same value into the text box, and presses the OK button.
2,When the OK button is pressed, clear the text box and display the next subject.
3,Repeat steps 1 and 2 5 times.
4,When the ok button is pressed the 5th time, the total number of characters from the 1st to the 5th times, in which the subject and the value entered by the user are incorrect, is displayed on the screen.
⚠️If the OK button is not pressed within 10 seconds, it is an error for the number of characters in the subject.
I left some clarifications as code comments
const subject = document.getElementById("subject");
const timer = document.getElementById("timer");
const input = document.getElementById("text");
const questionList = [
{ text: "Hello", pronunciation: "Hello" },
{ text: "World", pronunciation: "World" },
{ text: "HTML", pronunciation: "HTML" },
{ text: "CSS", pronunciation: "CSS" },
{ text: "PHP", pronunciation: "PHP" },
];
var question =
questionList[Math.floor(Math.random() * questionList.length)];
subject.textContent = question["text"];
var TIME = 10;
var index = 0;
var CorrectCount = 0;
var missTypeCount = 0;
var state;
const countdown = setInterval(function () {
if (TIME > 0) {
timer.textContent = "Time limit:" + --TIME;
}
if (TIME === 0) {
finish();
}
}, 1000);
document.addEventListener("keypress", function(e) {
if (e.key === question["pronunciation"].charAt(index) ) {
index++;
if (index == question["pronunciation"].length ) {
// Here is where a full correct word was completely written.
// Normally here is where you want to increment CorrectCount++ and reset TIME = 10
// However this is redundant, because you are performing these actions on check()
// I would advice to either keep this conditional, or the check() function, not both
CorrectCount;
}
} else {
missTypeCount++;
e.preventDefault();
}
});
function check() {
if(input.value === subject.textContent ) {
CorrectCount++;
init();
}
if (CorrectCount >= 5 ) {
finish();
}
}
function init() {
question =
questionList[Math.floor(Math.random() * questionList.length)];
subject.textContent = question["text"];
index = 0;
input.value = '';
input.focus();
// You need to set/reset the time to 10 here
TIME = 10;
}
function finish() {
clearInterval(countdown);
if (missTypeCount >= 0 ){
subject.textContent="Perfect"
}
// these conditionals are not doing what you want them to do.
// I believe you mean missTypeCount >= 1 && missTypeCount <= 3
if (missTypeCount >= 1 || missTypeCount >= 3 ){
subject.textContent="Good"
}
if (missTypeCount >= 4 || missTypeCount >= 8 ){
subject.textContent="Almost"
}
if (missTypeCount >= 9 ){
subject.textContent="Bad"
}
}
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="../css/test.css">
</head>
<body>
<div>
<div class="subject"><h1 id="subject"></h1></div>
<form name="typing" onsubmit="return false;">
<div class="text">
<input id="text" type="text" autocomplete="off" >
</div>
<div class="btn">
<input type="submit" value="ok" onclick="check();" >
</div>
</form>
<div class="timer">
<p id="timer">Time limit :10</p>
</div>
</div>
<script type="text/javascript" src="../js/test.js"></script>
</body>
</html>
You need to reset the TIME in your init function:
function init() {
question =
questionList[Math.floor(Math.random() * questionList.length)];
subject.textContent = question["text"];
index = 0;
TIME = 10;
input.value = '';
input.focus();
}
Otherwise the time will just keep on running.
Here is a fiddle to try it out.
But you have several other issues: When you misspelled and try to correct yourself within the time, you can not do this. The input is blocked. And you should set the cursor inside of your input when you load the page, or only start the timer when somebody starts typing. otherwise it is really hard to do it in time.
Use the php function time() or try something like that
<script>
var myVar;
var timer = document.getElementById("userInput");
var countDownSeconds;
function startTime(){
myVar = setInterval(start, 1000);
document.getElementById("timerr").innerHTML = timer.value;
countDownSeconds = timer.value;
}
function start(){
countDownSeconds--;
document.getElementById("timerr").innerHTML = countDownSeconds;
if (countDownSeconds == -1){
stop();
document.getElementById("timerr").innerHTML = "0";
}
}
function stop(){
clearInterval(myVar);
}
</script>

Pause and start JS countdown timer

I am trying to develop a centurion countdown timer for my website. It is a drinking game.
The way the timer works is: It is a 60 second countdown timer. Everytime the timer hits 0 it will +1 a shot counter and restart. It will do this 100 times.
The game is you must do 1 shot, every minute for 100 minutes. I am a beginner at JS and I am learning a lot, but I am seriously struggling to get this to work the way I want it to.
All I need is a "Start" Button, a "Pause" button and a "Reset" button but I can't seem to find a way to make these buttons work without messing the timer up.
Here is the HTML code:
<div class="inner">
<h1 class="heading alt">Centurions Timer</h1>
<p>1 Shot. Every Minute. 100 Minutes.</p>
<p>___________________________________</p>
<div id="timer">
<p id="seconds">60</p>
<p id="shots">0</p>
</div>
<input type="button" value="Start" onclick="timer()">
<input type="button" value="Pause" onclick="clearInterval(myTimer)">
</div>
and here is the JS code:
var seconds = 60;
var shots = 0;
var timer;
var c = 60;
function timer() {
timer = setInterval(myTimer, 1000)
}
function myTimer() {
document.getElementById("seconds").innerHTML = --c;
if (c == 0) {
shots = shots + 1;
c = 60;
}
document.getElementById("shots").innerHTML = shots;
}
If anyone could help me and show me what I am doing wrong and how I can make the code better, please do!
First, consider renaming either your method timer() or variable timer to disambiguate between the two.
Next, setInterval() returns an interval ID, which you store in timer.
clearInterval() takes the interval ID as the parameter, so try passing it the timer variable instead of myTimer (a function)
Little bit clean up needed. For clearInterval, u have to id of timer to clear
var seconds = 60;
var shots = 0;
var timer;
var c = 60;
function start() {
clearInterval(timer)
timer = setInterval(( ) =>{
updateUi()
}, 1000);
}
function pause() {
clearInterval(timer)
}
function updateUi() {
document.getElementById("seconds").innerHTML = --c;
if (c == 0) {
shots = shots + 1;
c = 60;
}
document.getElementById("shots").innerHTML = shots;
}
<div class="inner">
<h1 class="heading alt">Centurions Timer</h1>
<p>1 Shot. Every Minute. 100 Minutes.</p>
<p>___________________________________</p>
<div id="timer">
<p id="seconds">60</p>
<p id="shots">0</p>
</div>
<input type="button" value="Start" onclick="start()">
<input type="button" value="Pause" onclick="pause()">
</div>
You can also use Pub Sub model, to make code looks clean.
var seconds = 60;
var shots = 0;
var c = 60;
function Emitter() {
this.cb;
this.on = cb => {
this.cb = cb;
};
this.emit = () => {
this.cb && this.cb();
};
this.cancel = () => {
this.cb = null;
};
}
const emitter = new Emitter();
const tick = () => {
setInterval(() => {
emitter.emit();
}, 1000);
};
tick()
function start() {
emitter.on(updateUi);
}
function pause() {
emitter.cancel();
}
function updateUi() {
document.getElementById("seconds").innerHTML = --c;
if (c == 0) {
shots = shots + 1;
c = 60;
}
document.getElementById("shots").innerHTML = shots;
}
<div class="inner">
<h1 class="heading alt">Centurions Timer</h1>
<p>1 Shot. Every Minute. 100 Minutes.</p>
<p>___________________________________</p>
<div id="timer">
<p id="seconds">60</p>
<p id="shots">0</p>
</div>
<input type="button" value="Start" onclick="start()">
<input type="button" value="Pause" onclick="pause()">
</div>
<div class="inner">
<h1 class="heading alt">Centurions Timer</h1>
<p>1 Shot. Every Minute. 100 Minutes.</p>
<p>___________________________________</p>
<div id="timer">
<p id="minutes">100</p>
<p id="seconds">60</p>
<p id="shots">0</p>
</div>
<input type="button" value="START" onclick="start()">
<input type="button" value="PAUSE" onclick="pause()">
<input type="button" value="RESET" onclick="reset()">
</div>
Changed the onclick functions to something more meaningful. Added an extra button and some more logic to auto-stop when hitting the 100 minutes.
var seconds = 60,
minutes = 100,
shots = 0;
timer = "";
// this will just stop the timer, if you click start it will resume from where it left off
function pause() {
clearInterval(timer);
}
// resets seconds/minutes/shots, stops game
function reset() {
clearInterval(timer);
seconds = 60;
minutes = 100;
shots = 0;
timer = "";
document.getElementById("minutes").innerHTML = minutes;
document.getElementById("seconds").innerHTML = c;
document.getElementById("shots").innerHTML = shots;
}
// starts game from wherever it was left
function start() {
timer = setInterval(function() {
document.getElementById("seconds").innerHTML = c--;
if (c === 0) {
document.getElementById("minutes").innerHTML = --minutes;
// when 100 minutes are up, game will stop and reset
if (minutes === 0) {
reset();
}
shots++;
c = 60;
}
document.getElementById("shots").innerHTML = shots;
}, 1000)
}

Disable the click and reset it (Javascript Vanilla)

I have a problem. I created the following code! when you click on a button, a timer that lasts 3 seconds starts, the problem is that if I double click the button, the seconds go crazy, I would like to make sure that the click is reset as soon as the timer reaches 0! so that clicking again the timer always starts from 3 seconds!
document.getElementById("titolo").style.display="block"
count = 3 ;
setInterval(function(){
count--;
if(count>=0){
id = document.getElementById("titolo");
id.innerHTML = count;
}
if(count === 0){
document.getElementById("titolo").style.display="none" ;
}
},1000);
setInterval returns an ID that you can pass to clearInterval to cancel it. When the user clicks, cancel the existing ID and call setInterval again to reset it.
Capture the return value of setInterval so that later you can use it to call clearInterval.
You should disable (or hide) the button (or other element) that the user can click to start the count down.
Make sure to always declare your variables with var, let or const.
Don't use innerHTML when you only want to assign text (not HTML entities). For text (like the string representation of a counter) use textContent.
Here is how it could work:
let start = document.getElementById("start");
let id = document.getElementById("titolo");
start.addEventListener("click", function () {
start.disabled = true;
id.style.display = "block";
id.textContent = "3";
let count = 3;
let timer = setInterval(function(){
count--;
id.textContent = count;
if (count === 0) {
id.style.display = "none" ;
clearInterval(timer);
start.disabled = false;
}
}, 1000);
});
<button id="start">Start</button>
<div id="titolo"></div>
The function setInterval returns the unique id representing the interval. You can call the function clearInterval to delete that interval.
Example:
var intervalID = setInterval(function () { }, 0);
clearInterval(intervalID);
Example combined with your code:
var intervalID, count, dom = document.querySelector("#titolo");
document.querySelector("#button").addEventListener("click", onClick);
function onClick() {
clearInterval(intervalID);
dom.style.display = "block";
dom.textContent = 3;
count = 3;
intervalID = setInterval(function() {
count -= 1;
if (count >= 0) dom.textContent = count;
else {
dom.style.display = "none";
clearInterval(intervalID);
}
}, 1000);
}
<div id="titolo"></div>
<button id="button">Button</button>

JavaScript countdown timer not display button after reset

I am trying to create html5 app that have a timer. After time end in 10 second, it will display a button. Supposed to be, once user click on the button, a popup will displayed and it will count the button click in a variable and reset the timer. The process will loop again. The issue is, after user click on the button, and after the timer finished countdown for second time, the button is not displaying.
Here is the Js codes:
<!-- Timer countdown -->
<script type=text/javascript>
var clicks = 0;
function showTimer(selector, seconds)
{
var startTime = Date.now();
var interval;
function showRemaining()
{
var delta = Date.now() - startTime; // milliseconds
var deltaSeconds = delta / (1000);
if (deltaSeconds < seconds) {
// display minutes remaining
$(selector).text(Math.round(seconds - deltaSeconds));
} else {
$(selector).text(0);
clearInterval(interval);
}
}
interval = setInterval(showRemaining, 1000);
showRemaining();
}
$(document).ready(function()
{
showTimer("#countdown", 10);
});
setTimeout(function()
{
$("#proceed").show();
}, 10000);
//when click button
function onClick() {
clicks += 1;
document.getElementById("proceed").style.visibility="hidden";
alert("Getting the message");
document.getElementById("clicks").innerHTML = clicks;
showTimer("#countdown", 10);
};
</script>
This is the HTML:
<h1>Test</h1>
<br>
<p ><span id="countdown"></span><br>
Timer Here<br>
<button type="button" id="proceed" onclick="onClick()">Click</button><br>
<a id="clicks">0</a></p>
you forget to show your button again, the way you did it , it's going to hide. remove the setTimeout since you know the end of your timer and also can repeat it.
var clicks = 0;
var interval = -1;
function showTimer(selector, seconds)
{
var startTime = Date.now();
function showRemaining()
{
var delta = Date.now() - startTime; // milliseconds
var deltaSeconds = delta / (1000);
if (deltaSeconds < seconds) {
// display minutes remaining
$(selector).text(Math.round(seconds - deltaSeconds));
} else {
$(selector).text(0);
clearInterval(interval);
$("#proceed").show(); // Look at here
}
}
if( interval > -1 ) clearInterval(interval);
interval = setInterval(showRemaining, 1000);
showRemaining();
}
$(function() {
showTimer("#countdown", 10);
});
//when click button
function onClick() {
$("#proceed").hide();
alert("Getting the message");
$("#clicks").text(++clicks);
showTimer("#countdown", 10);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Test</h1>
<br>
<p >
<span id="countdown"></span><br>
Timer Here<br>
<button type="button" id="proceed" onclick="onClick()">Click</button><br>
<a id="clicks">0</a>
</p>
include jquery file link,
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js" type="text/javascript"></script>

How to set one minute counter in javascript?

In my project ,I have list of questions, for every question have three option answers.
After see the question if i want answer that question means click "show answer" button .
when I click button ,counter starts for one minute after one minute error will show .
can any one help ?
You could use something like this:
function gameLost() {
alert("You lose!");
}
setTimeout(gameLost, 60000);
UPDATE: pass function reference to setTimeout() instead of code string (did I really write it that way? O_o)
EDIT
To display the timer too (improved version, thanks to davin too):
<button onclick="onTimer()">Clickme</button>
<div id="mycounter"></div>
<script>
i = 60;
function onTimer() {
document.getElementById('mycounter').innerHTML = i;
i--;
if (i < 0) {
alert('You lose!');
}
else {
setTimeout(onTimer, 1000);
}
}
</script>
......
function timedOut() {
alert("Some error message");
}
// set a timer
setTimeout( timedOut , 60000 );
That basically sets a timer that will execute the given function after 60.000 miliseconds = 60 seconds = 1 minute
Edit: here's a quick, imperfect fiddle that also shows the countdown http://jsfiddle.net/HRrYG
function countdown() {
var seconds = 60;
function tick() {
var counter = document.getElementById("counter");
seconds--;
counter.innerHTML = "0:" + (seconds < 10 ? "0" : "") + String(seconds);
if( seconds > 0 ) {
setTimeout(tick, 1000);
} else {
alert("Game over");
}
}
tick();
}
// start the countdown
countdown();
You will want to use the setTimout function check out this article. https://developer.mozilla.org/En/Window.setTimeout Remember the timer is in milliseconds so for one minute is 60,000.
// this is the simplest way to one mint counter .this is also use in angular and oops
var i=60;
function coundown(){
setInterval(() => {
if (this.i == 0) {
return;
}
console.log(this.i--);
}, 1000);
}
// this function you can call when otp is comming or form submit and waiting for otp countdown
angular #javascript #typescript
you can try to use this
or visit for more details Demo
Demo2
function countdown() {
var seconds = 59;
function tick() {
var counter = document.getElementById("counter");
seconds--;
counter.innerHTML =
"0:" + (seconds < 10 ? "0" : "") + String(seconds);
if (seconds > 0) {
setTimeout(tick, 1000);
} else {
document.getElementById("verifiBtn").innerHTML = `
<div class="Btn" id="ResendBtn">
<button type="submit">Resend</button>
</div>
`;
document.getElementById("counter").innerHTML = "";
}
}
tick();
}
countdown();
<div class="btnGroup">
<span class="Btn" id="verifiBtn">
<button type="submit">Verify</button>
</span>
<span class="timer">
<span id="counter"></span>
</span>
</div>

Categories