Skip to content

Commit 527c31c

Browse files
Copilotalexr00
andcommitted
Optimize timestamp updates with variable intervals and visibility detection
Co-authored-by: alexr00 <38270282+alexr00@users.noreply.github.com>
1 parent 14856fd commit 527c31c

File tree

1 file changed

+63
-6
lines changed

1 file changed

+63
-6
lines changed

webviews/components/timestamp.tsx

Lines changed: 63 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,70 @@ export const Timestamp = ({ date, href }: { date: Date | string; href?: string }
1515
// Update the time string immediately
1616
setTimeString(dateFromNow(date));
1717

18-
// Set up an interval to update the time string every minute
19-
const intervalId = setInterval(() => {
20-
setTimeString(dateFromNow(date));
21-
}, 60000); // Update every 60 seconds
18+
// Calculate appropriate update interval based on how old the timestamp is
19+
const getUpdateInterval = () => {
20+
const now = Date.now();
21+
const timestamp = typeof date === 'string' ? new Date(date).getTime() : date.getTime();
22+
const ageInMinutes = (now - timestamp) / (1000 * 60);
23+
24+
// For very recent timestamps (< 1 hour), update every minute
25+
if (ageInMinutes < 60) {
26+
return 60000; // 1 minute
27+
}
28+
// For timestamps < 1 day old, update every 5 minutes
29+
else if (ageInMinutes < 60 * 24) {
30+
return 5 * 60000; // 5 minutes
31+
}
32+
// For older timestamps, update less frequently or not at all
33+
// since they likely show absolute dates
34+
else {
35+
return 15 * 60000; // 15 minutes
36+
}
37+
};
2238

23-
// Clean up the interval on component unmount
24-
return () => clearInterval(intervalId);
39+
const intervalDuration = getUpdateInterval();
40+
let intervalId: number;
41+
42+
const updateTimeString = () => {
43+
// Only update if the page is visible
44+
if (document.visibilityState === 'visible') {
45+
setTimeString(dateFromNow(date));
46+
}
47+
};
48+
49+
const startInterval = () => {
50+
intervalId = window.setInterval(updateTimeString, intervalDuration);
51+
};
52+
53+
const handleVisibilityChange = () => {
54+
if (document.visibilityState === 'visible') {
55+
// Page became visible, update immediately and restart interval
56+
setTimeString(dateFromNow(date));
57+
if (intervalId) {
58+
clearInterval(intervalId);
59+
}
60+
startInterval();
61+
} else {
62+
// Page became hidden, pause the interval
63+
if (intervalId) {
64+
clearInterval(intervalId);
65+
}
66+
}
67+
};
68+
69+
// Start the interval
70+
startInterval();
71+
72+
// Listen for visibility changes
73+
document.addEventListener('visibilitychange', handleVisibilityChange);
74+
75+
// Clean up on component unmount
76+
return () => {
77+
if (intervalId) {
78+
clearInterval(intervalId);
79+
}
80+
document.removeEventListener('visibilitychange', handleVisibilityChange);
81+
};
2582
}, [date]);
2683

2784
return href ? (

0 commit comments

Comments
 (0)