jquery倒计时
jQuery倒计时的实现方法
使用jQuery实现倒计时功能可以通过多种方式完成,以下是几种常见的实现方案:
基础倒计时功能
$(document).ready(function() {
let timeLeft = 60; // 设置倒计时秒数
function countdown() {
timeLeft--;
$('#countdown').text(timeLeft);
if(timeLeft <= 0) {
clearInterval(timer);
$('#countdown').text("时间到!");
}
}
let timer = setInterval(countdown, 1000);
});
带格式化的倒计时显示

function formatTime(seconds) {
let minutes = Math.floor(seconds / 60);
let secs = seconds % 60;
return `${minutes}:${secs < 10 ? '0' : ''}${secs}`;
}
$(function() {
let totalSeconds = 300; // 5分钟
let interval = setInterval(function() {
totalSeconds--;
$('#timer').text(formatTime(totalSeconds));
if(totalSeconds <= 0) {
clearInterval(interval);
alert("倒计时结束");
}
}, 1000);
});
可暂停的倒计时
let countdownTimer;
let remainingTime = 120;
function updateDisplay() {
$('#display').text(`${Math.floor(remainingTime/60)}分${remainingTime%60}秒`);
}
function startTimer() {
countdownTimer = setInterval(function() {
remainingTime--;
updateDisplay();
if(remainingTime <= 0) {
clearInterval(countdownTimer);
}
}, 1000);
}
$('#start').click(startTimer);
$('#pause').click(function() {
clearInterval(countdownTimer);
});
日期倒计时(距离特定日期)

function getTimeRemaining(endtime) {
let t = Date.parse(endtime) - Date.parse(new Date());
return {
'total': t,
'days': Math.floor(t / (1000 * 60 * 60 * 24)),
'hours': Math.floor((t / (1000 * 60 * 60)) % 24),
'minutes': Math.floor((t / 1000 / 60) % 60),
'seconds': Math.floor((t / 1000) % 60)
};
}
function initializeClock(id, endtime) {
let clock = $(id);
function updateClock() {
let t = getTimeRemaining(endtime);
clock.find('.days').text(t.days);
clock.find('.hours').text(t.hours);
clock.find('.minutes').text(t.minutes);
clock.find('.seconds').text(t.seconds);
if(t.total <= 0) {
clearInterval(timeinterval);
}
}
updateClock();
let timeinterval = setInterval(updateClock, 1000);
}
let deadline = new Date(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000);
initializeClock('#clockdiv', deadline);
注意事项
- 确保DOM加载完成后再执行倒计时代码,使用
$(document).ready()或简写$(function(){}) - 清除定时器使用
clearInterval()防止内存泄漏 - 考虑跨页面保持倒计时状态可使用
localStorage - 移动端需注意页面隐藏时定时器可能暂停的问题
扩展功能
添加动画效果增强用户体验:
$('#countdown').fadeOut(500).fadeIn(500);
添加完成回调:
if(timeLeft <= 0) {
clearInterval(timer);
if(typeof onComplete === 'function') {
onComplete();
}
}






