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
Here’s one way to get Pause/Resume working properly (and make the “-- PAUSED --” banner go away on resume) by swapping out your ad‐hoc DateTime math for a .NET Stopwatch. A Stopwatch has built-in Start/Stop so your elapsed time truly freezes when you pause, and keeps going when you resume.
You only need to replace your existing RunInterval() with the version below. Everything else (UI, beeps, state save, etc.) can stay exactly as it is.
powershell
# inside class TimerEngine
hidden RunInterval() {
# Mark the wall-clock start (for display & record keeping)
$intervalStartTime = Get-Date
# Use a Stopwatch to track elapsed, so Stop()/Start() pauses it cleanly
$stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
$isPaused = $false
$skipInterval = $false
while ($stopwatch.Elapsed.TotalSeconds -lt $this.Configuration.IntervalSeconds) {
# ---- Handle Keys ----
if ([Console]::KeyAvailable) {
$key = [Console]::ReadKey($true)
switch ($key.Key) {
'P' {
if ($stopwatch.IsRunning) {
$stopwatch.Stop()
$isPaused = $true
}
else {
$stopwatch.Start()
$isPaused = $false
}
}
'S' {
$skipInterval = $true
}
}
}
if ($skipInterval) { break }
# ---- Build data for UI ----
# derive a "virtual" current clock by adding elapsed to start
$liveTimestamp = $intervalStartTime.Add($stopwatch.Elapsed)
$renderData = @{
CompletedIntervals = $this.State.CompletedIntervals
CurrentIntervalNumber = $this.State.IntervalCounter
CurrentIntervalStartTime = $intervalStartTime
LiveTimestamp = $liveTimestamp
IsPaused = $isPaused
IntervalSeconds = $this.Configuration.IntervalSeconds
BeepVolumeScale = $this.Configuration.BeepVolumeScale
BeepCount = $this.Configuration.BeepCount
}
$this.UI.Render($renderData)
Start-Sleep -Milliseconds 100
}
# ---- Interval Complete ----
$this.InvokeBeep()
$this.State.AddCompletedInterval($intervalStartTime, $this.Configuration.IntervalSeconds)
$this.State.Save($this.Configuration.StateFilePath)
$this.UI.DisplayIntervalComplete()
}
colorYellow="
this.esc)[93m"hidden[string]
(
colorCyan="
this.esc)[36m"hidden[string]
(
colorReset="
::
new(
BeepVolumeScale,
What changed?
We create a [Stopwatch] instead of computing an end-time and constantly “extending” it.
On P we do Stop()/Start() on the stopwatch, and set $isPaused accordingly.
We compute the “current clock” for the UI by doing $intervalStartTime.Add($stopwatch.Elapsed)
so the HH:mm:ss.f line still makes sense.
When the stopwatch is stopped, Elapsed no longer moves, so your timer really pauses, and when you start it again it picks up exactly where you left off.
UI.Render sees IsPaused = $false as soon as you hit Resume, so the -- PAUSED -- banner disappears.
Drop this into your script in place of your old RunInterval() and you should have a rock-solid pause/resume. 🚀