I've been trying to utilize Timer in Swift and I've simplified it town to the following:
func startTimer () {
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(ViewController.test), userInfo: nil, repeats: true)
}
func test () {
print("FIRED")
}
I would like to call this from another function and have verified the startTimer function works, but the timer doesn't fire. Does this have something to do with the RunLoop? I'm fairly new to coding so any explanation would be appreciated.
Good Practice: In startTimer() check that the timer has not already been created and make the assignment. In stopTimer() check that the timer exists before calling invalidate, and set the timer back to nil.
Also, for your selector make sure you have the @objc
prefix. You should be able to get a working timer with the code provided. Happy coding!
class SomeClass {
var timer: Timer?
func startTimer() {
guard timer == nil else { return }
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(test), userInfo: nil, repeats: true)
}
func stopTimer() {
guard timer != nil else { return }
timer?.invalidate()
timer = nil
}
@objc func test() {
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With