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

求助:计分板JavaScript计时器倒计时显示异常问题

Hey there! Let's figure out why your timer is acting up and fix those annoying bugs together.

What's Causing the Issues?

  • The "-1" after hitting zero: Your timer probably doesn't stop when it reaches 00:00, or it decrements the seconds to -1 before handling the minute rollover, leading to negative numbers showing up.
  • The weird "1:0-1" flash: When you set it to 1:00, the code is likely subtracting 1 from seconds first (turning it to -1) before checking if it needs to roll the minute down and reset seconds to 59. That split second where seconds is -1 causes the wonky display.

Fixed Timer Code Example

Since you didn't share your full code, I'll use a common timer structure to show the fixes. You can adapt this to your existing scoreboard code:

// Initialize timer values
let minutes = 1;
let seconds = 0;
let timerInterval;

function startTimer() {
  // Clear any existing timer first to avoid multiple running instances
  if (timerInterval) clearInterval(timerInterval);

  timerInterval = setInterval(() => {
    // Handle minute/second rollover FIRST before decreasing seconds
    if (seconds === 0) {
      if (minutes === 0) {
        // Time's up! Stop the timer and lock display at 00:00
        clearInterval(timerInterval);
        updateTimerDisplay(0, 0);
        return;
      }
      // Decrease minute by 1 and reset seconds to 59
      minutes--;
      seconds = 59;
    } else {
      // Only decrease seconds if we don't need to roll over
      seconds--;
    }

    // Update the display with properly formatted numbers
    updateTimerDisplay(minutes, seconds);
  }, 1000);
}

function updateTimerDisplay(min, sec) {
  // Ensure seconds always show as two digits (no more "0-1" mess!)
  const formattedSec = sec < 10 ? `0${sec}` : sec;
  document.getElementById('scoreboard-timer').textContent = `${min}:${formattedSec}`;
}

Key Fixes Explained

  • Rollover Logic First: We check if seconds are 0 before decreasing them. This avoids ever getting a negative second value, which fixes the "1:0-1" flash entirely.
  • Stop at Zero: When both minutes and seconds hit 0, we immediately clear the interval and lock the display at 00:00, so it can't count down to -1.
  • Two-Digit Seconds Formatting: Ensuring seconds are always displayed as two digits keeps the timer looking clean and prevents odd formatting during rollover.

If your original code has a different structure, just apply these core ideas: handle rollover before decrementing values, stop the timer at 0, and format your display values properly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:16:22