js 实现每秒递增
实现每秒递增的 JavaScript 方法
使用 setInterval 定时器
let count = 0;
const interval = setInterval(() => {
count++;
console.log(count);
}, 1000);
// 清除定时器示例
// clearInterval(interval);
- 通过
setInterval设置每秒执行一次的函数 - 每次执行时将计数器
count加 1 - 1000 毫秒(1 秒)作为时间间隔参数
使用递归 setTimeout

let count = 0;
function increment() {
count++;
console.log(count);
setTimeout(increment, 1000);
}
increment();
- 定义递归函数
increment - 每次调用函数后设置新的 1 秒延时
- 避免
setInterval可能存在的执行堆积问题
基于 Date 对象的时间差计算

let count = 0;
let lastTime = Date.now();
function checkTime() {
const currentTime = Date.now();
if (currentTime - lastTime >= 1000) {
count++;
console.log(count);
lastTime = currentTime;
}
requestAnimationFrame(checkTime);
}
checkTime();
- 使用
requestAnimationFrame实现循环 - 通过比较时间戳确保精确的 1 秒间隔
- 适合需要与渲染帧同步的场景
使用异步函数与 await
async function increment() {
let count = 0;
while(true) {
await new Promise(resolve => setTimeout(resolve, 1000));
count++;
console.log(count);
}
}
increment();
- 利用
async/await语法实现同步风格的异步代码 - 每次循环等待 1 秒后执行递增
- 代码结构更清晰易读
注意事项
- 浏览器环境下建议使用
requestAnimationFrame避免后台标签页节流 - Node.js 环境可直接使用
setInterval或setTimeout - 清除定时器使用
clearInterval或clearTimeout防止内存泄漏 - 生产环境应考虑添加暂停/继续功能控制计数器






