[英]Why isn't my if function targeting the “timer” variable? I am trying to get it to alert/console “time is up” when the timer hits 0
如果有人有任何想法,請告訴我。 我希望我對此不要太討厭,但我已經玩了一段時間而且這對我不起作用。
function countdown() {
timer = 20;
timerId = setInterval(function() {
timer--;
console.log(timer);
$(".timer").html("Timer: " +timer);
}, 1000);
}
countdown();
if(timer == 0) {
console.log("Time is up");
alert("Time is up!");
incorrect ++;
$(".list-group").hide();
$(".Game").hide();
$(".timer").hide();
$(".timer").reset();
$(".Photo1").show();
}
創建一個函數來檢查每個間隔中的計時器變量
var timer, timerId ;
function countdown() {
timer = 20;
timerId = setInterval(function() {
timer--;
console.log(timer);
$(".timer").html("Timer: " +timer);
check();//call check function in every intervals
}, 1000);
}
countdown();
function check(){
if(timer == 0) {
clearTimeout(timerId );//clear timer function
console.log("Time is up");
alert("Time is up!");
incorrect ++;
$(".list-group").hide();
$(".Game").hide();
$(".timer").hide();
$(".timer").reset();
$(".Photo1").show();
}
}
將“timeup”代碼移動到間隔中。
function countdown() {
timer = 20;
timerId = setInterval(function() {
timer--;
console.log(timer);
$(".timer").html("Timer: " +timer);
if(timer == 0) {
console.log("Time is up");
alert("Time is up!");
incorrect ++;
$(".list-group").hide();
$(".Game").hide();
$(".timer").hide();
$(".timer").reset();
$(".Photo1").show();
}
}, 1000);
}
countdown();
如果我正確地理解了你的問題,那么要實現這個目標,你需要移動觸發alert("Time is up!");
的邏輯alert("Time is up!");
和console.log()
行為進入間隔回調,如下所示:
function countdown() { var timer = 20; var incorrect = 0; var timerId = setInterval(function() { timer--; console.log(timer); $(".timer").html("Timer: " +timer); // place alert and console log logic here // so that it is run when timer equals zero if(timer === 0) { console.log("Time is up"); alert("Time is up!"); incorrect ++; $(".list-group").hide(); $(".Game").hide(); $(".timer").hide(); $(".timer").reset(); $(".Photo1").show(); } }, 1000); } countdown();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
您可以在countdown()
檢查timer變量,並使用clearInterval()
來停止時間,如下所示:
var timerId = setInterval(countdown, 1000); var timer = 20; var incorrect = 0; function countdown() { timer--; console.log(timer); //$(".timer").html("Timer: " +timer); if(timer == 0) { clearInterval(timerId); console.log("Time is up"); //alert("Time is up!"); incorrect ++; /*$(".list-group").hide(); $(".Game").hide(); $(".timer").hide(); $(".timer").reset(); $(".Photo1").show();*/ } } countdown();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.