I have used timers before and they worked, but ever since NSTimer changed to Timer, my timers refuse to work. The code I have tried is as follows:
override func viewDidLoad() {
super.viewDidLoad()
_ = Timer(timeInterval: 3, target: self, selector: #selector(test), userInfo: nil, repeats: true)
}
func test() {
print("The timer worked")
}
The test function is never called and I have no idea why. I have also tried initializing it first and using it like so:
var followUpTimer:Timer!
override func viewDidLoad() {
super.viewDidLoad()
followUpTimer = Timer(timeInterval: 3, target: self, selector: #selector(test), userInfo: nil, repeats: true)
}
func test() {
print("The timer worked")
}
But that does not work either. What am I doing wrong? All the answers I find online show that this is the correct way of doing it.
(NS)Timer needs a run loop to work properly. You can add the timer programmatically to the loop but it's more convenient to use the method
Timer.scheduledTimer(withTimeInterval:...
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