You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让JavaScript计时器与浏览器性能同步,避免延迟?

问题描述

我的电脑后台运行着一款卡顿的应用,导致Firefox浏览器性能受影响。我用以下代码实现了一个JavaScript倒计时计时器:

let seconds = 10;
let countdown = setInterval(() => {
  if (seconds <= 0) return clearInterval(countdown);
  document.querySelector("#timer").textContent = seconds;
  seconds--;
}, 1000);

性能正常时计时器运行良好,但性能不佳时,倒计时延迟在1-3秒之间波动。如何让倒计时与浏览器性能同步,确保每次准确递减1秒,避免延迟?

解决方案

核心是基于绝对时间戳计算剩余时间,而非依赖setInterval的执行间隔——后者在浏览器卡顿会被推迟,导致累计误差,而时间戳是不受运行环境影响的绝对参考。

改进后的代码:

// 设置总倒计时时长(秒)
const totalCountdownSeconds = 10;
// 记录倒计时启动的初始时间戳
const startTimestamp = Date.now();

const countdownTimer = setInterval(() => {
  // 计算从启动到现在已流逝的秒数
  const elapsedSeconds = Math.floor((Date.now() - startTimestamp) / 1000);
  // 算出当前剩余的秒数
  const remainingSeconds = totalCountdownSeconds - elapsedSeconds;

  if (remainingSeconds <= 0) {
    clearInterval(countdownTimer);
    document.querySelector("#timer").textContent = '0';
    return;
  }

  document.querySelector("#timer").textContent = remainingSeconds;
}, 100);

细节说明

  • 改用Date.now()的时间差计算剩余时间,不管浏览器卡顿导致setInterval推迟多久执行,每次计算的剩余时间都是准确的,不会出现累计延迟。
  • 把执行间隔从1000ms缩短到100ms,这样即使浏览器偶尔卡顿,也能快速校准显示的数值,避免出现跳秒或长时间不更新的情况,让倒计时视觉上更平滑。
  • 抛弃原代码中自减的seconds变量,彻底避免了因执行延迟导致的计数偏差问题。

内容的提问来源于stack exchange,提问作者ProOfficial

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 21:40:14