jquery 计时
jQuery 计时器实现方法
使用jQuery实现计时功能可以通过多种方式完成,以下是常见的几种方法:
setInterval方法
let seconds = 0;
const timer = setInterval(function() {
seconds++;
$('#display').text(seconds + '秒');
}, 1000);
// 停止计时
$('#stop').click(function() {
clearInterval(timer);
});
setTimeout递归方法
let count = 0;
function startTimer() {
setTimeout(function() {
count++;
$('#counter').text(count);
startTimer(); // 递归调用
}, 1000);
}
startTimer();
jQuery动画计时
let time = 0;
function updateTimer() {
$('#timer').animate({opacity: 0.5}, 1000, function() {
time++;
$(this).text(time).css('opacity', 1);
updateTimer();
});
}
updateTimer();
日期对象计算
const startTime = new Date();
setInterval(function() {
const currentTime = new Date();
const elapsed = Math.floor((currentTime - startTime)/1000);
$('#elapsed').text(elapsed + '秒');
}, 1000);
倒计时实现
let countdown = 60;
const timer = setInterval(function() {
countdown--;
$('#countdown').text(countdown);
if(countdown <= 0) {
clearInterval(timer);
alert('时间到!');
}
}, 1000);
格式化时间显示
function formatTime(seconds) {
const mins = Math.floor(seconds/60);
const secs = seconds % 60;
return (mins < 10 ? '0' : '') + mins + ':' + (secs < 10 ? '0' : '') + secs;
}
注意事项
- 清除计时器使用clearInterval或clearTimeout
- 避免内存泄漏,在页面卸载时清除所有计时器
- 考虑使用requestAnimationFrame实现更精确的动画计时
- 移动端注意节流处理,减少性能消耗







