Files
peworkshop/utils/timerService.js
T
2025-03-15 16:30:04 +00:00

75 lines
2.1 KiB
JavaScript

/**
* Centralized timer service to ensure consistent timing across the application
*/
// Store the hunt timer information in localStorage for persistence
export const setHuntTimer = (startTime, endTime = null, isActive = true) => {
const timerData = {
startTime,
endTime,
isActive,
lastUpdated: new Date().toISOString(),
};
localStorage.setItem("huntTimerData", JSON.stringify(timerData));
};
// Clear the hunt timer completely
export const clearHuntTimer = () => {
localStorage.removeItem("huntTimerData");
localStorage.removeItem("teamHuntStartTime"); // Remove legacy timer as well
};
// Get the current hunt timer data
export const getHuntTimer = () => {
try {
const timerData = localStorage.getItem("huntTimerData");
if (!timerData) {
// Try to migrate from old format if exists
const legacyStartTime = localStorage.getItem("teamHuntStartTime");
if (legacyStartTime) {
return {
startTime: legacyStartTime,
endTime: null,
isActive: true,
lastUpdated: new Date().toISOString(),
};
}
return null;
}
return JSON.parse(timerData);
} catch (error) {
console.error("Error parsing hunt timer data:", error);
return null;
}
};
// Calculate and format elapsed time from a given start time
export const formatElapsedTime = (startTimeStr) => {
if (!startTimeStr) return "00:00:00";
const startTime = new Date(startTimeStr).getTime();
const now = Date.now();
const elapsed = Math.floor((now - startTime) / 1000);
// Handle negative time (shouldn't happen in normal usage)
if (elapsed < 0) return "00:00:00";
const hours = Math.floor(elapsed / 3600)
.toString()
.padStart(2, "0");
const minutes = Math.floor((elapsed % 3600) / 60)
.toString()
.padStart(2, "0");
const seconds = Math.floor(elapsed % 60)
.toString()
.padStart(2, "0");
return `${hours}:${minutes}:${seconds}`;
};
// Hook function to use in components to get formatted elapsed time
export const useElapsedTime = (startTime, isActive = true) => {
if (!startTime || !isActive) return "00:00:00";
return formatElapsedTime(startTime);
};