js实现倒退
实现倒计时功能
使用JavaScript实现倒计时功能可以通过setInterval或setTimeout结合日期计算来完成。以下是几种常见的倒计时实现方式。
基础倒计时(固定时长)
let count = 10; // 倒计时秒数
const timer = setInterval(() => {
console.log(count);
count--;
if (count < 0) {
clearInterval(timer);
console.log('倒计时结束');
}
}, 1000);
目标时间倒计时
计算当前时间与目标时间的差值,实现精确到天、小时、分钟和秒的倒计时。

function countdown(targetDate) {
const timer = setInterval(() => {
const now = new Date();
const distance = targetDate - now;
if (distance <= 0) {
clearInterval(timer);
console.log('倒计时结束');
return;
}
const days = Math.floor(distance / (1000 * 60 * 60 * 24));
const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((distance % (1000 * 60)) / 1000);
console.log(`${days}天 ${hours}小时 ${minutes}分钟 ${seconds}秒`);
}, 1000);
}
const targetDate = new Date('2024-12-31T23:59:59');
countdown(targetDate);
使用requestAnimationFrame
对于需要更平滑动画效果的倒计时,可以使用requestAnimationFrame。

let count = 10;
function animateCountdown() {
console.log(count);
count--;
if (count >= 0) {
requestAnimationFrame(animateCountdown);
} else {
console.log('倒计时结束');
}
}
animateCountdown();
格式化输出
如果需要将倒计时显示在网页上,可以结合DOM操作。
<div id="countdown"></div>
<script>
let count = 10;
const countdownElement = document.getElementById('countdown');
const timer = setInterval(() => {
countdownElement.textContent = count;
count--;
if (count < 0) {
clearInterval(timer);
countdownElement.textContent = '倒计时结束';
}
}, 1000);
</script>
暂停和继续功能
为倒计时添加暂停和继续功能,增强交互性。
let count = 10;
let timer;
let isPaused = false;
function startCountdown() {
timer = setInterval(() => {
if (!isPaused) {
console.log(count);
count--;
if (count < 0) {
clearInterval(timer);
console.log('倒计时结束');
}
}
}, 1000);
}
function togglePause() {
isPaused = !isPaused;
console.log(isPaused ? '已暂停' : '继续');
}
startCountdown();
这些方法涵盖了从简单到复杂的倒计时实现,适用于不同场景需求。






