Certainly! You can achieve this by dynamically adjusting the interval of the setInterval function based on the elapsed time. Here's a solution that changes the interval to every minute for the first hour and then every hour after that.
<div x-data="{
local_lastSavedDiffForHumans: '',
lastSavedDiffForHumans() {
const date = luxon.DateTime.fromISO(Alpine.store('global_data').lastSaved);
return date.toRelative();
},
updateInterval: 60000, // Start with 1 minute interval
updateLastSavedDiffForHumans() {
this.local_lastSavedDiffForHumans = this.lastSavedDiffForHumans();
const date = luxon.DateTime.fromISO(Alpine.store('global_data').lastSaved);
const now = luxon.DateTime.now();
const diffInMinutes = now.diff(date, 'minutes').minutes;
if (diffInMinutes >= 60) {
this.updateInterval = 3600000; // Change to 1 hour interval after 1 hour
} else {
this.updateInterval = 60000; // Keep 1 minute interval for the first hour
}
},
startUpdating() {
this.updateLastSavedDiffForHumans();
setInterval(() => {
this.updateLastSavedDiffForHumans();
}, this.updateInterval);
}
}" x-init="startUpdating()">
<span x-text="local_lastSavedDiffForHumans"></span>
</div>
Explanation:
-
Initialization:
-
local_lastSavedDiffForHumans: Stores the human-readable time difference. -
updateInterval: Initially set to 1 minute (60000 milliseconds).
-
-
lastSavedDiffForHumans:
- Converts the ISO date from the global store to a human-readable relative time using Luxon.
-
updateLastSavedDiffForHumans:
- Updates
local_lastSavedDiffForHumanswith the latest relative time. - Calculates the difference in minutes between the current time and the last saved time.
- Adjusts the
updateIntervalbased on the elapsed time:- If the difference is 60 minutes or more, set the interval to 1 hour (3600000 milliseconds).
- Otherwise, keep the interval at 1 minute.
- Updates
-
startUpdating:
- Calls
updateLastSavedDiffForHumansimmediately to set the initial value. - Sets up a
setIntervalto callupdateLastSavedDiffForHumansat the specifiedupdateInterval.
- Calls
This approach ensures that the interval dynamically adjusts based on the elapsed time, meeting your requirement of updating every minute for the first hour and then every hour thereafter.