Set a 10-second timer for each subject input - javascript

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>

Related

How to fix clearInterval() not stopping the interval?

I made an interval connected to a button that only runs when you have a certain amount of money and lemonade. Then I created an if statement that makes it so that when you run out of lemonade, then the interval stops. I used clearInterval() and for some reason the interval doesn't stop, and the number of lemonade goes into the negatives. Obviously you can't have a negative amount of something!
I've looked at all of the other questions with similar problems to me, but they didn't really answer my question. They all have different variables and it was hard to find an answer pertaining to my code.
Here's my code:
let autoBtnTwo = document.getElementById("autoBtnTwo");
let lemonade = 0;
let btnTwo = document.getElementById("btnTwo")
function btnTwoCost() {
wallet.removeCash(20);
update();
document.getElementById("lemonade").innerHTML = lemonade += 30
}
function double() {
if (wallet.getCash() >= 50) {
wallet.addCash(2)
update();
document.getElementById("lemonade").innerHTML = lemonade -= 1;
}
}
function autoLemonade() {
if (wallet.getCash() >= 3000) {
wallet.removeCash(3000);
var myint = setInterval(double, 1000);
autoBtnTwo.disabled = false;
update();
}
if (wallet.getCash() <= 2999) {
autoBtnTwo.disabled = true;
}
if (lemonade <= 0) {
autoBtnTwo.disabled = true;
btnTwo.disabled = true;
}
}
function stopInterval() {
var myint = setInterval(double, 1000);
if (lemonade <= 0) {
clearInterval(myint);
stopInterval();
}
}
function thousand() {
wallet.addCash(1000)
update();
if (wallet.getCash() >= 3000) {
autoBtnTwo.disabled = false;
}
}
function Wallet() {
return {
addCash: function(val) {
number += val;
},
getCash: function() {
return number;
},
removeCash: function(val) {
number -= val;
}
}
}
var number = 0;
const wallet = new Wallet();
var SUFFIXES = 'KMBTqQsSOND';
function update() {
document.getElementById('number').textContent = getSuffixedNumber(wallet.getCash());
}
function getSuffixedNumber(num) {
var power = Math.floor(Math.log10(num));
var index = Math.floor(power / 3)
num = num / Math.pow(10, (index * 3)); // first 3 digits of the number
return num.toFixed(1) + (SUFFIXES[index - 1] || ''); // default to no suffix if it gets an out of bounds index
}
<button onclick="autoLemonade()" class="chocolate-bar-auto" id="autoBtnTwo" disabled>
Hire worker: <br> -$3000<br> Sells Lemonade
</button>
<button onclick="thousand()">to get to $3000 for testing </button>
<button onclick="btnTwoCost()"> buy lemonade -$20</button>
<button onclick="double()">sell lemonade </button>
<div class="cash-div">
Cash: <div id="number">0</div>
</div>
<div class="lemonade-div">
Lemonade: <div id="lemonade">0</div>
</div>
Sorry if this version is glitchy. All of the code I used to prevent the glitches makes the code longer, which it is already long enough. press the $3,000 button 4 times, then the buy lemonade, and then the hire worker button and you will see what happens once it gets to 0.
The interval should stop adding money, and stop reducing the amount of lemonade when lemonade reaches 0, but instead it keeps going into the negatives.

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

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>

Starting timer when clicking first card of memory game

Ok I am trying to wrap up a project and the only thing holding me back is it that they call for the timer to start on clicking a match game. The timer starts when the HTML file loads which is not what the project wants and I have tried some methods but ends up freezing the game. I want the timer to be able to start when clicking a card.
var open = [];
var matched = 0;
var moveCounter = 0;
var numStars = 3;
var timer = {
seconds: 0,
minutes: 0,
clearTime: -1
};
//Start timer
var startTimer = function () {
if (timer.seconds === 59) {
timer.minutes++;
timer.seconds = 0;
} else {
timer.seconds++;
};
// Ensure that single digit seconds are preceded with a 0
var formattedSec = "0";
if (timer.seconds < 10) {
formattedSec += timer.seconds
} else {
formattedSec = String(timer.seconds);
}
var time = String(timer.minutes) + ":" + formattedSec;
$(".timer").text(time);
};
This is the code for clicking on a card. I have tried to include a startTimer code into this but doesn't work.
var onClick = function() {
if (isValid( $(this) )) {
if (open.length === 0) {
openCard( $(this) );
} else if (open.length === 1) {
openCard( $(this) );
moveCounter++;
updateMoveCounter();
if (checkMatch()) {
setTimeout(setMatch, 300);
} else {
setTimeout(resetOpen, 700);
}
}
}
};
And this class code I use for my HTML file
<span class="timer">0:00</span>
Try this: https://codepen.io/anon/pen/boWQbe
All you needed to do was remove resetTimer() call from the function that happens on page load and then just do a check in the onClick (of card) to see if the timer has started yet. timer.seconds == 0 && timer.minutes == 0.

Onclick reset setInterval

<!DOCTYPE html>
<html>
<head>
<script>
function timer(x) {
if (x == 1) {
//reset timer
}
var i = 0;
var timer = setInterval(function() {
var x = document.getElementById("demo").innerHTML = i;
i = i + 1;
}, 500);
}
</script>
</head>
<body>
<p id="demo">hello</p>
<button type="button" onclick="timer(0)">change</button>
<button type="button" onclick="timer(1)">reset</button>
</body>
</html>
I want to reset timer onclick . e.g. if setIntervaltime is set to 5 sec and 3 seconds are elapsed ,after that if some on click on reset button it should start gain from 5 seconds.How to do this.
Keep the return value of setTimeout somewhere that you can get it again (currently you are storing it in a local variable, so it goes away when the function ends)
Call clearTimeout(timer);
Call setTimeout with whatever arguments you want again.
As already Quentin mentioned, use clearInterval to solve your problem.
Wrap it within an if.else.. statement like
if(x == 1) {
clearTimeout(timeout);
}
else {
timeout = setInterval..... // otherwise even after resetting
// it will continue to increment the value
}
Complete Code:
var timeout; // has to be a global variable
function timer(x) {
var i = 0;
if (x == 1) {
clearTimeout(timeout);
document.getElementById("demo").innerHTML = i;
} else {
timeout = setInterval(function () {
var x = document.getElementById("demo").innerHTML = i;
i = i + 1;
}, 1000);
}
}
JSFiddle

Display diffrent image depending on timer

I'm trying to display a different image depending on the timer's result and can't find a way through. So far I have a start and stop button, but when I click stop, I want to use the value the timer is on and display an image(on alertbox or the webpage itself) depending on that value.
if( timer =>60){
img.src("pizzaburnt.jpg");
}elseif (timer <=30){
img.src("pizzaraw.jpg");
}
else{
img.src("pizzaperfect.jpg
}
///Time
var check = null;
function printDuration() {
if (check == null) {
var cnt = 0;
check = setInterval(function () {
cnt += 1;
document.getElementById("para").innerHTML = cnt;
}, 1000);
}
}
//Time stop
function stop() {
clearInterval(check);
check = null;
document.getElementById("para").innerHTML = '0';
}
**HTML**
<td>
Timer :<p id="para">0</p>
</td>
Any advice or dicussion would be great, thanks.
Something like this would work better and it's more compact:
var img = document.getElementById("image");
var imageSrcs = ['pizzaRaw.jpg', 'pizzaPerfect.jpg', 'pizzaBurnt.jpg'];
var imageIndex = 0;
var interval = setInterval(animate, 30000); //change image every 30s
var animate = function() {
//change image here
//using jQuery:
img.src(imageSrcs[imageIndex]);
imageIndex++; //move index for next image
if (imageIndex == imageSrcs.length) {
clearInterval(interval); //stop the animation, the pizza is burnt
}
}
animate();
Reason you wouldn't want to use an increment variable and a 1 second timer is because your just conflating your logic, spinning a timer, and making a bit of a mess when all you really want is the image to change every 30 seconds or whenever.
Hope this helps.
You need an <img> tag in your HTML like this:
<html>
<body>
Timer: <p id="para">0</p>
Image: <img id="image" />
</body>
</html>
And the Javascript code will be like:
var handle;
var timerValue = 0;
var img = document.getElementById( "image" );
var para = document.getElementById("para");
function onTimer() {
timerValue++;
para.innerHTML = timerValue;
if ( timerValue >= 60 ) {
img.src( "pizzaburnt.jpg" );
}else if ( timer <= 30 ) {
img.src( "pizzaraw.jpg" );
} else {
img.src("pizzaperfect.jpg" );
}
}
function start () {
if ( handle ) {
stop();
}
timerValue = 0;
setInterval( onTimer, 1000 );
}
function stop () {
if ( handle ) {
clearInterval ( handle );
}
}
Please make sure that these 3 files are in the same directory as your HTML file:
pizzaburnt.jpg
pizzaraw.jpg
pizzaperfect.jpg

Categories