Swift 3 Timer does not work

I am trying to use Timer in Swift, and I simplified it by 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 it from another function and check the startTimer function, but the timer does not work. Is this related to RunLoop? I am new to coding, so any explanation would be appreciated.

+5
source share
1 answer

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() { } } 
+12
source

Source: https://habr.com/ru/post/1261794/


All Articles