Web游戏HH:MM:SS格式剩余时间显示问题:数字调用length返回undefined
Hey there! Let's sort out that time formatting issue you're facing. I totally get how frustrating it is when you have a clear idea for displaying remaining time, but small JavaScript quirks throw a wrench in things.
The Root of Your Problem
You mentioned that ss1.length was returning undefined instead of 1 or 2. That's because you were trying to access the length property directly on an integer—and numbers don't have a length attribute in JavaScript. It won't automatically convert to a string for you; you have to do that explicitly.
A Clean Solution for HH:MM:SS Formatting
Instead of manually checking string lengths and adding separators, let's use a more reliable approach with a helper function to pad numbers to two digits. Here's how to implement it step-by-step:
1. Handle WebSocket Data & Calculate Remaining Seconds
First, when you receive the timestamp from your WebSocket, calculate how many seconds are left until expiration. Make sure to account for timestamp units (most backends use seconds, but if yours uses milliseconds, adjust accordingly):
// Listen for WebSocket messages yourWebSocket.onmessage = (event) => { const game = JSON.parse(event.data); // Use either expire1 or expire2 depending on your needs const expireTimestamp = game.expire1; updateTimerDisplay(expireTimestamp); }; function updateTimerDisplay(expireTimestamp) { // Convert current time to seconds (match backend timestamp unit) const currentTimeInSeconds = Date.now() / 1000; // Calculate remaining seconds, ensure it's not negative let remainingSeconds = Math.max(0, expireTimestamp - currentTimeInSeconds);
2. Break Down Seconds into Hours, Minutes, Seconds
Next, convert the total remaining seconds into hours, minutes, and individual seconds:
const hours = Math.floor(remainingSeconds / 3600); const minutes = Math.floor((remainingSeconds % 3600) / 60); const seconds = Math.floor(remainingSeconds % 60);
3. Pad Digits to Two Characters
Create a simple helper function to convert numbers to strings and pad them with a leading zero if they're single-digit. This eliminates the need to check string lengths manually:
// Helper to pad numbers to 2 digits const padZero = (num) => num.toString().padStart(2, '0');
4. Format & Display the Time
Finally, combine the padded values into the HH:MM:SS format and update your DOM:
const formattedTime = `${padZero(hours)}:${padZero(minutes)}:${padZero(seconds)}`; // Replace with your actual DOM element ID document.getElementById('game-timer').textContent = formattedTime; }
5. Add Real-Time Updates (Optional)
If you want the timer to tick every second, wrap the update function in an interval:
// Start the interval when the game starts let timerInterval = setInterval(() => { // Re-fetch the latest expire timestamp or use the one stored updateTimerDisplay(game.expire1); }, 1000); // Don't forget to clear the interval when the game ends! // clearInterval(timerInterval);
Key Notes to Remember
- Double-check your backend's timestamp unit: if it uses milliseconds instead of seconds, remove the
/ 1000fromDate.now(). - Using
Math.max(0, ...)ensures your timer never shows negative values once the game expires. - The
padStartmethod is supported in all modern browsers, but if you need to support older ones, you can fall back to a manual check like:const padZero = (num) => num < 10 ? `0${num}` : num.toString();
内容的提问来源于stack exchange,提问作者Alexander Farber

