js 实现每秒递增
实现每秒递增的 JavaScript 方法
使用 setInterval
通过 setInterval 函数可以轻松实现每秒递增的功能。以下是一个简单的示例代码:
let counter = 0;
const intervalId = setInterval(() => {
counter++;
console.log(counter);
}, 1000);
// 如果需要停止递增,可以调用 clearInterval(intervalId);
使用 setTimeout 递归
另一种方法是使用 setTimeout 递归调用,这样可以避免 setInterval 可能带来的时间漂移问题:
let counter = 0;
function increment() {
counter++;
console.log(counter);
setTimeout(increment, 1000);
}
increment();
使用 requestAnimationFrame
如果需要更精确的时间控制(尤其是在动画场景中),可以使用 requestAnimationFrame,但需要手动计算时间间隔:
let counter = 0;
let lastTime = 0;
function increment(timestamp) {
if (timestamp - lastTime >= 1000) {
counter++;
console.log(counter);
lastTime = timestamp;
}
requestAnimationFrame(increment);
}
requestAnimationFrame(increment);
使用 Date 对象
如果需要确保时间严格准确,可以结合 Date 对象来实现:

let counter = 0;
let startTime = Date.now();
function increment() {
const currentTime = Date.now();
if (currentTime - startTime >= 1000) {
counter++;
console.log(counter);
startTime = currentTime;
}
requestAnimationFrame(increment);
}
increment();
注意事项
- 如果需要在页面显示递增的值,可以将
console.log替换为更新 DOM 元素的代码。 - 使用
setInterval或setTimeout时,需要注意清理定时器以避免内存泄漏。 - 对于高性能场景,
requestAnimationFrame是更好的选择。






