有沒有辦法讓 setInterval 一次只作業一次?我的代碼應該這樣作業:
- 您手動輸入秒數;
- “div”用作計時器并運行直到達到 0。
如果您單擊“單擊我”一次,它將按預期作業。但是,如果您以足夠快的速度多次單擊按鈕,則偶數偵聽器將與您單擊的次數一樣同時作業。
let button = document.getElementById('button');
let input = document.getElementById('input');
let timer = document.getElementById('timer');
function timerRunner () {
let startTime = input.value;
if (startTime <= 0) {
console.log('The number is <=0')
} else {
do {
timer.textContent = startTime;
let counter = startTime;
let interval = setInterval(()=> {
console.log(counter);
counter--;
timer.textContent = counter;
if (counter === 0) {
clearInterval(interval);
}
}, 1000);
} while (typeof (timer.textContent) == "number");
}
}
button.addEventListener('click', timerRunner)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.centeralizer {
display: block;
width: 200px;
margin: 20vh auto;
}
#input {
display: block;
margin-bottom: 35px;
width: 150px;
}
#button {
display: inline-block;
margin-right: 35%;
}
#timer {
display: inline-block;
}
</style>
<script src="index.js" defer></script>
</head>
<body>
<div class="centeralizer">
<input id="input" placeholder="Input the number" type="number">
<button id="button">Click me</button>
<div id="timer">0</div>
</div>
</body>
</html>
uj5u.com熱心網友回復:
您應該將運行間隔存盤在上部范圍內,如果再次按下按鈕,則清除它。
const button = document.getElementById('button');
const input = document.getElementById('input');
const timer = document.getElementById('timer');
let interval = null;
function startTimer() {
const startTime = input.value;
if (startTime <= 0) {
console.log('The number is <= 0');
return;
}
let counter = startTime;
timer.textContent = startTime;
if (interval) clearInterval(interval);
interval = setInterval(() => {
timer.textContent = --counter;
console.log(counter);
if (counter === 0) clearInterval(interval);
}, 1000);
}
button.addEventListener('click', startTimer)
uj5u.com熱心網友回復:
您可以添加一個布爾變數isRunning來跟蹤計時器是否正在運行。您可以在計時器運行時將其設定為開啟,并在計時器完成時將其關閉。單擊按鈕時檢查它是否打開,如果是則回傳。您可以防止觸發計時器的多個實體。
let button = document.getElementById('button');
let input = document.getElementById('input');
let timer = document.getElementById('timer');
var isRunning = false;
function timerRunner () {
if(isRunning) {
return; //return if timer is already running
}
isRunning = true; //specify that the timer is running
let startTime = input.value;
if (startTime <= 0) {
console.log('The number is <=0')
} else {
do {
timer.textContent = startTime;
let counter = startTime;
let interval = setInterval(()=> {
console.log(counter);
counter--;
timer.textContent = counter;
if (counter === 0) {
isRunning = false; //specify that the timer is not running and can be run again
clearInterval(interval);
}
}, 1000);
} while (typeof (timer.textContent) == "number");
}
}
button.addEventListener('click', timerRunner)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/357863.html
標籤:javascript 设置间隔 清除间隔
下一篇:如何在Vue中增加回圈
