Good practice. In startTimer (), verify that the timer has not yet been created and is not running the task. In stopTimer (), check if a timer exists before calling invalidate and set the timer to zero.
Also, for your selector, make sure you have the @obj 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() { } }
source share