我終其一生都無法弄清楚如何讓它無錯誤地作業。
下面代碼中的按鈕需要做三件事。
- 單擊時開始倒計時(有效)
- 自動結束倒計時,當它到達 0 時自動重置(有效)
- 如果在倒計時中間單擊它會過早重置自身(作業,有點)
錯誤:當反復點擊時,它會啟動多個倒計時,或多或少會中斷。如果反復單擊,它需要自行重置或開始倒計時。倒計時不應該超過一個。
只要人們按下按鈕,等待一秒鐘,然后再次按下它以停止它,它就可以正常作業。
我遇到的錯誤是,如果有人垃圾郵件點擊它,它會啟動多個倒計時并且通常只是破壞按鈕。我嘗試了很多不同的方法來修復它,這是我得到的最接近的方法。
var i = 29;
let running=false;
$("#startButton").click(function () {
if(running==false){
var countdown = setInterval(function () {
$("#startButton").text("Reset Timer");
running=true;
$("#stopWatch").html(i);
i--;
if (i <0)
{
$("#startButton").text("Start Timer");
running=false;
clearInterval(countdown);
i = 29;
$("#stopWatch").html(i);
}
$("#startButton").click(function () {
$("#startButton").text("Start Timer");
running=false;
clearInterval(countdown);
i = 29;
$("#stopWatch").html(i 1);
});
}, 1000);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="stopWatch">30</div>
<button id="startButton">Start Timer</button>
uj5u.com熱心網友回復:
歡迎來到 Stack Overflow @William!
我不確定這意味著什么:Reset itself prematurely if its clicked in the middle of a countdown(works, sort of)。但我設法修復了您在點擊垃圾郵件按鈕時的錯誤,對于第 3 項,我只是從初始狀態重置倒計時。請參閱下面的片段:
// Get attribute value from div `stopwatch`. This is for resetting from default value.
var initial = $('#stopWatch').attr("value");
// Assigned initial value to var i.
var i = initial;
$("#stopWatch").html(i);
let running = false;
// Created a separate function to call from button click.
function run(timer = true) {
if (timer) {
running = true;
$("#startButton").text("Reset Timer");
$("#stopWatch").html(i);
var countdown = setInterval(function () {
i--;
$("#stopWatch").html(i);
if (i <= 0) {
running = false;
$("#startButton").text("Start Timer");
clearInterval(countdown);
i = initial;
$("#stopWatch").html(i);
}
}, 1000);
} else {
running = false;
clearInterval(countdown);
i = 0;
$("#startButton").text("Start Timer");
}
}
$("#startButton").click(function () {
// Check if its not running and var i is not 0
if(!running && i != 0) {
run();
// Check if its running and var i is not 0 to ensure that if someone spam the button it just reset the countdown.
} else if (running && i != 0) {
// Will return the else{} on function run().
run(false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="stopWatch" value="30"></div>
<button id="startButton">Start Timer</button>
在片段上添加了一些評論。如果您有任何問題,請隨時詢問。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/437477.html
標籤:javascript html jQuery
