I currently have a button that starts the timer with a function “vibrate” which gives haptic feedback to the user repeated on an infinite interval. When the user taps the button, it will stop and invalidate the timer “only after the timer has run out.” If the user taps the button again before the timer runs out, there are now two timers running at the same time. One is now giving a false vibrate ( out of sync with the animation ) to the user. I am new to swift and started learning 2-3 months ago and have not been able to figure out this issue. I don’t want to tell a user they have wait a specific length of time till they can tap the button again or disable it before they can tap it again. I would prefer to “kill” the timer as soon as the button is tapped by the user the second time. Thank you!
private enum Constants {
static let duration: Double = 3.5
}
@State private var isAnimated = false
@Binding var isVibrating: Bool
if isVibrating {
vibrate() // initial vibrate
}
Timer.scheduledTimer(withTimeInterval: Constants.duration, repeats: true) { timer in
// if statement is needed to prevent last false vibrate
if isAnimated {
if isVibrating {
vibrate() // repeating vibrates
}
}
if !isAnimated {
// BUG: This waits till the rest of the time runs out on the timer
print("invalidate")
timer.invalidate()
}
}
}