go runtime_error ai_generated true

panic: time: Reset called on timer with negative duration

ID: go/panic-timer-reset-negative-duration

Also available as: JSON · Markdown · 中文
85%Fix Rate
85%Confidence
1Evidence
2023-06-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
Go 1.15 active
Go 1.16 active
Go 1.17 active
Go 1.18 active
Go 1.19 active
Go 1.20 active
Go 1.21 active
Go 1.22 active
Go 1.23 active

Root Cause

Calling Timer.Reset() with a negative duration value causes a runtime panic in Go's time package.

generic

中文

使用负持续时间值调用 Timer.Reset() 会导致 Go 的 time 包中的运行时恐慌。

Official Documentation

https://pkg.go.dev/time#Timer.Reset

Workarounds

  1. 95% success Use time.Duration(math.Abs(float64(d))) to ensure non-negative duration before calling Reset()
    Use time.Duration(math.Abs(float64(d))) to ensure non-negative duration before calling Reset()
  2. 90% success Check duration with if d < 0 { d = 0 } before timer.Reset(d)
    Check duration with if d < 0 { d = 0 } before timer.Reset(d)
  3. 85% success Use time.NewTimer() with a positive duration and stop it explicitly instead of resetting
    Use time.NewTimer() with a positive duration and stop it explicitly instead of resetting

中文步骤

  1. Use time.Duration(math.Abs(float64(d))) to ensure non-negative duration before calling Reset()
  2. Check duration with if d < 0 { d = 0 } before timer.Reset(d)
  3. Use time.NewTimer() with a positive duration and stop it explicitly instead of resetting

Dead Ends

Common approaches that don't work:

  1. 80% fail

    time.Duration() does not validate sign; negative values remain negative.

  2. 90% fail

    time.AfterFunc() also panics on negative duration; same underlying issue.

  3. 75% fail

    Panic recovery masks the bug but timer state is corrupted; leads to unpredictable behavior.