当用户在输入中输入内容时,我试图设置一个递减计时器。但是,当用户编写新内容时,它会重新启动,我正在努力使其正常工作。
我认为。一个人会解决这个问题,但显然不会。
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>
答案 0 :(得分:3)
移动计数器并测试tId:
var counter = 15, x, span = document.getElementById("timer");
function myTimer() {
if (!x) x = window.setInterval(function() {
if (counter === 0) window.clearInterval(x);
counter--;
span.innerHTML = counter >= 0 ? counter : "OUT OF TIME"
}, 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>
答案 1 :(得分:2)
您需要一个全局布尔变量ALTER TABLE "<your-table>" ADD "<your-cf>"."_0" VARCHAR(1);
ALTER TABLE "<your-table>" DROP COLUMN "<your-cf>"."_0";
。在函数的第一行,检查其值,如果为isCounterRunning
,则在执行任何操作之前将其返回;如果为true
,请将其设置为true,然后执行函数中的其余代码。
false
var isCounterOn = false
function myTimer() {
if(isCounterOn) return;
else{
isCounterOn = true
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);
答案 2 :(得分:1)
您必须在startInterval外部初始化x,以便随后可以覆盖它。而且,顾名思义,one()
仅会触发一个事件。如果您想在每次事件发生时赶上,请使用on()
var counter = 15;
var x = 0;
var span = document.getElementById("timer");
function myTimer() {
window.clearInterval(x);
startInterval();
}
function startInterval() {
counter = 15;
span.innerHTML = counter;
x = setInterval(function() {
counter--;
if (counter >= 0) {
span.innerHTML = counter;
}
if (counter === 0) {
span.innerHTML = "OUT OF TIME";
window.clearInterval(x);
}
}, 1000);
}
$("#wrapper input").on("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>