方法一:使用?requestAnimationFrame
?和時間戳計算平均 FPS
let frameCount = 0;
let lastTime = performance.now();
let fps = 0;
let isSlow = false; // 是否卡頓的標志function calculateFPS(currentTime) {frameCount++;// 每隔大約 1000 毫秒(1秒)計算一次 FPSif (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;// 計算瞬時 FPSconst instantFPS = Math.round(1000 / deltaTime);// 判斷是否卡頓,這里可以設置一個更嚴格的閾值,比如 45 FPSif (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);