Reputation: 3965
I am trying to reset a counter when failing a test. My fail()
function is called when something goes wrong after clicking a button. The same button is used for activating the counter, this causes the counter to be 1 instead of 0 when failing. Is there a way to reset the counter without it adding the last click up again?
This is my code example:
$(document).ready(() => {
$('#btn-check').click(() => {
if (checkAnimal(counter)) {
// Do something.
}
else {
fail(); // Reset counter.
}
counter++; // Counter adds 1 again.
})
})
var counter = 0;
const checkAnimal = (counter) => {
if (counter < 1) {
// First animal.
}
else {
// Other animals (different treatment).
}
}
const fail = () => {
counter = 0;
}
<script src="https://code.jquery.com/jquery-3.5.0.js"
integrity="sha256-r/AaFHrszJtwpe+tHyNi/XCfMxYpbsRg2Uqn0x3s2zc=" crossorigin="anonymous">
</script>
Upvotes: 1
Views: 41
Reputation: 699
Your problem is that counter++
is outside of if/else statement, so after executing else (fail() function), your code will run once more counter++
.
To avoid that, you will have to replace counter++ to one of the if statement.
Also you are not returning anything in fail()
function.
$(document).ready(() => {
$('#btn-check').click(() => {
if (checkAnimal(counter)) {
// Do something.
}
else {
fail(); // Doesn't return anything.
}
// Counter is outside of statement
counter++;
})
})
Upvotes: 1