Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I cannot get my Swift 3 Timer to fire

Tags:

timer

swift3

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.

like image 316
Cody Lucas Avatar asked Dec 14 '25 21:12

Cody Lucas


1 Answers

(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:...
like image 78
vadian Avatar answered Dec 16 '25 23:12

vadian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!