0

I have a timer in my app that is publishing every 0.1 seconds to allow a smooth progress bar animation.

I have 2 if statements to check when the timer has reached 10 seconds to play a sound, and again at 0 seconds

However, it seems like the conditions are never being met. I can cast the timer to an Int, but the conditions are met 10 times as opposed to 1.

I suspect this is because the timer is a Double? I can publish every second and use an Int - this works but the progress bar is choppy.

How do I go about fixing this and still allow me to have a smooth progress bar

struct TimerComponent: View {
    
    @State var progress: Double = 0
    @Binding var countdownTimer: Double
    @Binding var timerRunning: Bool
    let timer = Timer.publish(every: 0.1, on: .main, in: .common).autoconnect()
    
    var body: some View {
        
        
        ZStack {
            
            CircularProgressComponent(progress: progress, timerRunning: $timerRunning)
                .frame(width: 120, height: 120)
            
            Text("\(Int(countdownTimer))")
                .onReceive(timer){ _ in
                    if countdownTimer > 0 && timerRunning {
                        countdownTimer -= 0.1
                        progress = 1 - Double(countdownTimer)/60
                        if countdownTimer == 10.0 {
                            SoundManager.instance.playSound(sound: .flatline)
                        }
                    } else if countdownTimer == 0.0 {
                        timerRunning = false
                        countdownTimer = -1
                    }
                }
                .font(Font.custom("AnnieUseYourTelescope-Regular", size: 40))
                .frame(minWidth: 80, maxHeight: 50)
                .padding(10)
                .foregroundColor(.black)
                .cornerRadius(10)
                .shadow(radius: 50)
        }
        
    }
} 
TheDoctor
  • 13
  • 4
  • 3
    Change your countdownTimer to Int and have it track tenths of seconds. So 10 seconds will be represented by 100 and you’ll subtract 1 every tick. – vacawama Jul 09 '23 at 14:19
  • 2
    https://stackoverflow.com/questions/588004/is-floating-point-math-broken – Rob Napier Jul 09 '23 at 22:03

0 Answers0