js实现倒退
实现倒计时功能
在JavaScript中实现倒计时功能通常涉及设置一个时间间隔,并在每个间隔内更新显示的时间。以下是几种常见的实现方式:
使用setInterval方法
let countdown = 10;
const timer = setInterval(() => {
console.log(countdown);
countdown--;
if (countdown < 0) {
clearInterval(timer);
console.log('倒计时结束');
}
}, 1000);
这段代码会从10开始每秒递减,直到0时停止并输出"倒计时结束"。
使用requestAnimationFrame
对于需要更精确控制的动画倒计时,可以使用requestAnimationFrame:

let startTime = Date.now();
const duration = 10000; // 10秒倒计时
function updateCountdown() {
const elapsed = Date.now() - startTime;
const remaining = Math.max(0, duration - elapsed);
console.log(Math.ceil(remaining / 1000));
if (remaining > 0) {
requestAnimationFrame(updateCountdown);
} else {
console.log('倒计时结束');
}
}
updateCountdown();
显示在网页上
将倒计时显示在HTML页面上:
<div id="countdown">10</div>
<script>
let timeLeft = 10;
const countdownElement = document.getElementById('countdown');
const timer = setInterval(() => {
timeLeft--;
countdownElement.textContent = timeLeft;
if (timeLeft <= 0) {
clearInterval(timer);
countdownElement.textContent = '时间到!';
}
}, 1000);
</script>
带格式的时间显示
如果需要显示分钟和秒:

function formatTime(seconds) {
const mins = Math.floor(seconds / 60);
const secs = seconds % 60;
return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}
let totalSeconds = 120; // 2分钟
setInterval(() => {
totalSeconds--;
console.log(formatTime(totalSeconds));
if (totalSeconds <= 0) clearInterval(this);
}, 1000);
暂停和继续功能
实现可以暂停和继续的倒计时:
let remainingTime = 60;
let timer;
let isPaused = false;
function startCountdown() {
timer = setInterval(() => {
if (!isPaused) {
remainingTime--;
console.log(remainingTime);
if (remainingTime <= 0) clearInterval(timer);
}
}, 1000);
}
function togglePause() {
isPaused = !isPaused;
}
startCountdown();
// 调用togglePause()可以暂停或继续倒计时
使用Promise实现
用Promise包装倒计时功能:
function countdown(seconds) {
return new Promise((resolve) => {
let current = seconds;
const timer = setInterval(() => {
console.log(current);
current--;
if (current < 0) {
clearInterval(timer);
resolve();
}
}, 1000);
});
}
countdown(5).then(() => console.log('倒计时完成'));
这些方法提供了不同场景下实现JavaScript倒计时功能的方案,可以根据具体需求选择适合的方式。






