I am trying to set a decrementing timer when a user inputs something in an input. However, I am struggling to get it to properly work, when a user writes something new it restarts.
I thought .one would take care of this but apparently not.
function myTimer() {
var counter = 15;
var x = window.setInterval(function() {
counter--;
if (counter >= 0) {
span = document.getElementById("timer");
span.innerHTML = counter;
}
if (counter === 0) {
span.innerHTML = "OUT OF TIME";
window.clearInterval(x);
}
}, 1000);
}
$("#wrapper input").one("change paste keyup", myTimer);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="timer">15</span><br>
<div id="wrapper">
<input class="something" type="text"><br>
<input class="somethingelse" type="text">
</div>
input. Therefore it fires once per element. As such the timer will reset as soon as the second element is interacted with. You either need to create separate timers or check if the timer is already running when the second event fires so it doesn't get reset.isCounterRunningand on first line of your function check its value, if it's true return out the function before doing anything, and if it's false, set it to true and then do the rest of your code in your function.