倒计时 jquery
使用 jQuery 实现倒计时功能
jQuery 可以通过操作 DOM 和定时器轻松实现倒计时功能。以下是几种常见的倒计时实现方式:

基础倒计时(从固定秒数开始)
$(document).ready(function() {
let count = 60; // 倒计时60秒
const countdown = setInterval(function() {
$('#countdown').text(count);
count--;
if (count < 0) {
clearInterval(countdown);
$('#countdown').text('时间到!');
}
}, 1000);
});
指定结束时间的倒计时
$(document).ready(function() {
const endTime = new Date();
endTime.setMinutes(endTime.getMinutes() + 5); // 5分钟后结束
const timer = setInterval(function() {
const now = new Date().getTime();
const distance = endTime - now;
const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((distance % (1000 * 60)) / 1000);
$('#countdown').text(minutes + "分 " + seconds + "秒");
if (distance < 0) {
clearInterval(timer);
$('#countdown').text('倒计时结束');
}
}, 1000);
});
带样式的倒计时显示
$(document).ready(function() {
let timeLeft = 300; // 5分钟=300秒
const timer = setInterval(function() {
const minutes = Math.floor(timeLeft / 60);
const seconds = timeLeft % 60;
$('#minutes').text(minutes < 10 ? '0' + minutes : minutes);
$('#seconds').text(seconds < 10 ? '0' + seconds : seconds);
if (--timeLeft < 0) {
clearInterval(timer);
$('#timer').html('<span>时间到!</span>');
}
}, 1000);
});
带暂停和继续功能的倒计时
$(document).ready(function() {
let timeLeft = 60;
let timer;
let isRunning = false;
function updateDisplay() {
$('#time').text(timeLeft);
}
function startTimer() {
if (!isRunning) {
isRunning = true;
timer = setInterval(function() {
timeLeft--;
updateDisplay();
if (timeLeft < 0) {
clearInterval(timer);
$('#time').text('完成');
isRunning = false;
}
}, 1000);
}
}
function pauseTimer() {
clearInterval(timer);
isRunning = false;
}
$('#start').click(startTimer);
$('#pause').click(pauseTimer);
updateDisplay();
});
实现要点
- 使用
setInterval创建定时器,每隔1秒更新显示 - 通过
clearInterval停止倒计时 - 计算剩余时间并格式化为分钟和秒
- 添加事件处理程序实现交互功能
- 确保在倒计时结束时清除定时器并显示结束信息
注意事项
- 定时器可能存在微小误差,不是精确的1秒间隔
- 页面不可见时(如切换标签页),浏览器可能降低定时器频率
- 对于重要计时场景,建议使用服务器时间而非客户端时间
- 移动设备上,屏幕关闭可能导致定时器暂停






