jquery计时器
jQuery计时器的实现方法
使用jQuery实现计时器功能可以通过多种方式完成,以下是几种常见的实现方法:
基于setInterval的计时器

var seconds = 0;
var timer = setInterval(function() {
seconds++;
$('#timer').text(seconds + '秒');
}, 1000);
// 停止计时器
$('#stop').click(function() {
clearInterval(timer);
});
倒计时实现
var countdown = 60;
var timer = setInterval(function() {
countdown--;
$('#countdown').text(countdown + '秒');
if (countdown <= 0) {
clearInterval(timer);
$('#countdown').text('时间到!');
}
}, 1000);
可暂停和继续的计时器

var seconds = 0;
var timer;
var isRunning = false;
$('#start').click(function() {
if (!isRunning) {
isRunning = true;
timer = setInterval(function() {
seconds++;
$('#timer').text(seconds + '秒');
}, 1000);
}
});
$('#pause').click(function() {
if (isRunning) {
clearInterval(timer);
isRunning = false;
}
});
格式化时间显示
function formatTime(seconds) {
var hours = Math.floor(seconds / 3600);
var minutes = Math.floor((seconds % 3600) / 60);
var secs = seconds % 60;
return (hours < 10 ? "0" + hours : hours) + ":" +
(minutes < 10 ? "0" + minutes : minutes) + ":" +
(secs < 10 ? "0" + secs : secs);
}
var seconds = 0;
setInterval(function() {
seconds++;
$('#formatted-timer').text(formatTime(seconds));
}, 1000);
注意事项
- 使用
clearInterval清除计时器时,需要确保变量是全局可访问的 - 计时器会继续运行即使页面被隐藏或最小化
- 在单页应用中切换视图时,需要手动清除计时器
- 长时间运行的计时器可能会因为JavaScript的单线程特性而出现微小误差
性能优化建议
对于需要高精度的计时器,可以考虑使用requestAnimationFrame替代setInterval:
var startTime = Date.now();
function updateTimer() {
var elapsed = Date.now() - startTime;
$('#high-precision-timer').text((elapsed/1000).toFixed(3) + '秒');
requestAnimationFrame(updateTimer);
}
updateTimer();
这种方法能提供更流畅的动画效果和更高的时间精度。






