js 实现计时器

使用 setTimeout 实现单次计时器
setTimeout(() => {
console.log('计时结束');
}, 3000); // 3秒后执行
使用 setInterval 实现循环计时器
let counter = 0;
const timer = setInterval(() => {
console.log(`已过去 ${++counter} 秒`);
if (counter >= 5) {
clearInterval(timer);
}
}, 1000); // 每秒执行一次
高性能 requestAnimationFrame 计时器
let startTime = null;
function step(timestamp) {
if (!startTime) startTime = timestamp;
const elapsed = timestamp - startTime;
if (elapsed < 3000) { // 运行3秒
console.log(Math.floor(elapsed / 1000));
window.requestAnimationFrame(step);
}
}
window.requestAnimationFrame(step);
精确到毫秒的计时器实现
class PrecisionTimer {
constructor(duration, callback) {
this.start = performance.now();
this.timer = setInterval(() => {
const elapsed = performance.now() - this.start;
callback(elapsed);
if (elapsed >= duration) clearInterval(this.timer);
}, 16); // 约60fps
}
}
new PrecisionTimer(5000, (ms) => {
console.log(`已过去 ${ms.toFixed(2)} 毫秒`);
});
暂停/恢复功能的计时器实现
class PausableTimer {
constructor(interval, callback) {
this.remaining = interval;
this.timerId = null;
this.start = null;
this.callback = callback;
}
startTimer() {
this.start = Date.now();
this.timerId = setTimeout(this.callback, this.remaining);
}
pause() {
clearTimeout(this.timerId);
this.remaining -= Date.now() - this.start;
}
resume() {
this.startTimer();
}
}
使用 Web Worker 实现后台计时器
worker.js:

let interval;
self.onmessage = (e) => {
if (e.data === 'start') {
let counter = 0;
interval = setInterval(() => {
self.postMessage(++counter);
}, 1000);
} else if (e.data === 'stop') {
clearInterval(interval);
}
};
主线程:
const worker = new Worker('worker.js');
worker.onmessage = (e) => {
console.log(`Worker计时: ${e.data}秒`);
};
worker.postMessage('start');
// 停止计时
// worker.postMessage('stop');






