fix the pause function.
the timer does not pause and the pasue text does not dissapear
this happens: i press pause the pause text appears. thats it. everything just goes on
<#
.SYNOPSIS
An interactive, persistent, and highly configurable productivity timer.
.DESCRIPTION
A flicker-free console timer with advanced features, refactored into a modular,
class-based architecture for improved readability and maintainability.
- Configurable interval duration, beep sound, and beep count via parameters.
- Interactive controls: Pause/Resume (P) and Skip (S).
- Persistent State: Autosaves after each interval and prompts to load on startup.
.PARAMETER IntervalSeconds
The duration of each work interval in seconds. Default is 600 (10 minutes).
.PARAMETER BeepVolumeScale
Sets the beep pitch on a scale of 1 (low) to 10 (high). Default is 5.
.PARAMETER BeepCount
The number of times to beep at the end of an interval. Max is 10. Default is 3.
.USAGE
# Run with defaults (10 min interval, medium beep, 3 beeps)
.\StudyClock_Refactored.ps1
code
# Run a 30-minute interval with a loud, single beep
.\StudyClock_Refactored.ps1 -IntervalSeconds 1800 -BeepVolumeScale 8 -BeepCount 1
#================================================================================
param(
[Parameter(HelpMessage = "The duration of each work interval in seconds.")]
[int]$IntervalSeconds = 600,
code
[Parameter(HelpMessage = "Sets the beep pitch on a scale of 1 (low) to 10 (high).")]
[ValidateRange(1, 10)]
[int]$BeepVolumeScale = 5,
[Parameter(HelpMessage = "The number of times to beep at the end of an interval.")]
[ValidateRange(1, 10)]
[int]$BeepCount = 3
Manages the application's persistent state (completed intervals).
class TimerState {
[System.Collections.Generic.List[IntervalRecord]]CompletedIntervals[int]IntervalCounter
code
TimerState() {
$this.CompletedIntervals = [System.Collections.Generic.List[IntervalRecord]]::new()
$this.IntervalCounter = 1
}
# Adds a new completed interval and increments the counter.
AddCompletedInterval([datetime]$StartTime, [int]$Duration) {
$record = [IntervalRecord]::new($this.IntervalCounter, $StartTime, $Duration)
$this.CompletedIntervals.Add($record)
$this.IntervalCounter++
}
# Saves the current state to a JSON file.
Save([string]$Path) {
$this | ConvertTo-Json -Depth 5 | Set-Content -Path $Path
}
# Static method to load state from a file or create a new one.
static [TimerState] Load([string]$Path) {
if (-not (Test-Path $Path)) {
return [TimerState]::new()
}
$response = Read-Host "Load previous session? (Y/n)"
if ($response -match '^[nN]') { # Made the check case-insensitive
return [TimerState]::new()
}
try {
$jsonData = Get-Content -Path $Path | ConvertFrom-Json
$state = [TimerState]::new()
$state.IntervalCounter = $jsonData.IntervalCounter
# Re-hydrate the generic list with strongly-typed IntervalRecord objects
# Check if CompletedIntervals exists and is not null before iterating
if ($null -ne $jsonData.CompletedIntervals) {
foreach ($item in $jsonData.CompletedIntervals) {
# The StartTime is saved as a string, so we need to parse it back to a datetime
# to create a valid IntervalRecord object. This was a subtle bug in the previous version.
$startTimeAsDateTime = [datetime]::ParseExact($item.StartTime, 'HH:mm', $null)
$record = [IntervalRecord]::new(
$item.Number,
$startTimeAsDateTime,
$item.IntendedDurationSeconds
)
$state.CompletedIntervals.Add($record)
}
}
return $state
}
catch {
Write-Warning "Could not load or parse state file. Starting new session."
return [TimerState]::new()
}
}
}
Manages all console input and output (UI).
class StudyClockUI {
# Private members for ANSI escape codes
hidden [string]esc=[char]27hidden[string]cursorHome = "(this.esc)[H"
hidden [string](colorGreen = "this.esc)[32m"
hidden [string](colorRed = "this.esc)[91m"
hidden [string]($this.esc)[0m"
code
# Prepares the console for the application.
Setup() {
[System.Console]::CursorVisible = $false
Clear-Host
}
# Restores the console to its original state.
Cleanup() {
[System.Console]::CursorVisible = $true
}
# Renders the entire UI frame.
Render([hashtable]$UIData) {
$sb = [System.Text.StringBuilder]::new()
# 1. Build the dynamic Info Header
$intervalInfo = "Interval: $($UIData.IntervalSeconds)s"
if ($UIData.IntervalSeconds -eq 600) { $intervalInfo += " (default)" }
$volumeInfo = "Volume: $($UIData.BeepVolumeScale)"
if ($UIData.BeepVolumeScale -eq 5) { $volumeInfo += " (default)" }
$countInfo = "Beeps: $($UIData.BeepCount)"
if ($UIData.BeepCount -eq 3) { $countInfo += " (default)" }
[void]$sb.AppendLine("$($this.colorYellow)$intervalInfo | $volumeInfo | $countInfo$($this.colorReset)")
[void]$sb.AppendLine()
# 2. Build the completed intervals list
[void]$sb.AppendLine("$($this.colorYellow)#n [Start] [Progress] [Current]$($this.colorReset)")
[void]$sb.AppendLine("$($this.colorYellow)---------------------------------------$($this.colorReset)")
foreach ($interval in $UIData.CompletedIntervals) {
$totalMinutes = [math]::Round($interval.IntendedDurationSeconds / 60)
$line = "#$($interval.Number)".PadRight(3) + " $($interval.StartTime) ($totalMinutes/$totalMinutes)"
[void]$sb.AppendLine("$($this.colorGreen)$line$($this.colorReset)")
}
# 3. Build the current interval line
$elapsed = $UIData.LiveTimestamp - $UIData.CurrentIntervalStartTime
$totalMinutes = [math]::Round($UIData.IntervalSeconds / 60)
$minutesPassed = [math]::Floor($elapsed.TotalMinutes)
$startString = $UIData.CurrentIntervalStartTime.ToString('HH:mm')
$progressString = "($minutesPassed/$totalMinutes)".PadRight(10)
$currentString = $UIData.LiveTimestamp.ToString('HH:mm:ss.f')
$currentLine = "#$($UIData.CurrentIntervalNumber)".PadRight(3) + " $startString $progressString $currentString"
if ($UIData.IsPaused) {
$currentLine += " $($this.colorRed)-- PAUSED --$($this.colorReset)"
}
[void]$sb.AppendLine("$($this.colorCyan)$currentLine$($this.colorReset)")
[void]$sb.AppendLine()
[void]$sb.AppendLine("Controls: [P] Pause/Resume | [S] Skip Interval | [Ctrl+C] Exit")
Write-Host -NoNewline ($this.cursorHome + $sb.ToString())
}
# Displays a message between intervals.
DisplayIntervalComplete() {
Clear-Host
}
}
The main application engine, orchestrating all other components.
class TimerEngine {
[StudyClockConfiguration]Configuration[TimerState]State
[StudyClockUI]$UI
2. Create the main engine with the specified configuration.
timer=[TimerEngine]::new(config)
3. Start the timer. The engine's try/finally block handles cleanup.
$timer.Start()
Assistant
The Problem:
The pause functionality isn't working correctly because the $isPaused variable is being used incorrectly. When you press 'P', it toggles $isPaused, but this change isn't reflected in the loop's behavior. The timer continues to run because the condition (Get-Date) -lt $intervalEndTime is still being evaluated, and $intervalEndTime is only updated when paused.
The Fix:
We need to introduce a separate mechanism to control the flow of time when the timer is paused. Here's the corrected code:
Replaced $intervalEndTime with $remainingSeconds: Instead of checking if the current time is less than the end time, we now calculate the remaining seconds and decrement it when not paused.
Added $pauseStartTime: Tracks when the pause started to calculate the pause duration.
Pause Logic: When paused, we stop decrementing $remainingSeconds. When unpaused, we adjust $intervalStartTime by the pause duration, effectively "skipping over" the paused time.
Removed the hacky $intervalEndTime.AddMilliseconds(100): No longer needed, as the timer now correctly freezes when paused.
With these changes:
Pressing 'P' will correctly pause the timer, and the "-- PAUSED --" text will appear.
The timer will resume when 'P' is pressed again, and the text will disappear.
The interval will accurately reflect the time spent working, excluding pauses.
Run the updated script, and the pause functionality should work as expected!