方法一:使用 requestAnimationFrame
和时间戳计算平均 FPS
let frameCount = 0;
let lastTime = performance.now();
let fps = 0;
let isSlow = false; // 是否卡顿的标志
function calculateFPS(currentTime) {
frameCount++;
// 每隔大约 1000 毫秒(1秒)计算一次 FPS
if (currentTime - lastTime >= 1000) {
fps = Math.round((frameCount * 1000) / (currentTime - lastTime));
frameCount = 0;
lastTime = currentTime;
// 判断是否卡顿
if (fps < 30) { // 假设 30 FPS 为卡顿阈值
console.log(`当前帧率 ${fps},页面卡顿!`);
isSlow = true;
// 这里可以添加卡顿后的处理逻辑,比如降低动画效果等
} else {
console.log(`当前帧率 ${fps},页面流畅。`);
isSlow = false;
}
}
// 请求下一帧,继续循环
requestAnimationFrame(calculateFPS);
}
// 启动监测
requestAnimationFrame(calculateFPS);
// 如果需要,可以在某个时刻停止监测
// cancelAnimationFrame(animationFrameId);
方法二:监测单帧渲染时间(Delta Time)
let lastFrameTime = performance.now();
let isSlow = false;
function checkFrameRate(currentTime) {
const deltaTime = currentTime - lastFrameTime;
lastFrameTime = currentTime;
// 计算瞬时 FPS
const instantFPS = Math.round(1000 / deltaTime);
// 判断是否卡顿,这里可以设置一个更严格的阈值,比如 45 FPS
if (instantFPS < 45) {
console.log(`单帧耗时 ${deltaTime.toFixed(2)}ms,瞬时帧率 ${instantFPS},可能卡顿!`);
isSlow = true;
} else {
console.log(`单帧耗时 ${deltaTime.toFixed(2)}ms,瞬时帧率 ${instantFPS},流畅。`);
isSlow = false;
}
// 请求下一帧,继续循环
requestAnimationFrame(checkFrameRate);
}
// 启动监测
requestAnimationFrame(checkFrameRate);