Chen Li Yong Chen Li Yong -4 years ago 96
Swift Question

Why my timer doesn't want to fire at the specified interval?

I have these two functions in my class:

func setTimer () {
alertEndTimer = Timer.init(timeInterval: 10, target: self, selector: #selector(hideAlert), userInfo: nil, repeats: false);
print ("NOW: \(now)")
print ("FIRE DATE: \(alertEndTimer!.fireDate)");
}

@IBAction func hideAlert () {
doSomething();
}


The result of the console is like this:

NOW: 2017-03-01 03:32:36 +0000
FIRE DATE: 2017-03-01 03:32:46 +0000


I then put a break point on
doSomething();
. But after waiting for like 1 minute, the break point is not called at all. I also have checked whether the timer
isValid()
, and it returns true. So why doesn't my function get called?

Answer Source

From the documentation:

Use the init(timeInterval:invocation:repeats:) or init(timeInterval:target:selector:userInfo:repeats:) class method to create the timer object without scheduling it on a run loop. (After creating it, you must add the timer to a run loop manually by calling the add(_:forMode:) method of the corresponding RunLoop object.)

That is you need to call

RunLoop.current.add(alertEndTimer, forMode: .defaultRunLoopMode)

in order to start the timer.


You could create the timer using the scheduledTimer method to start it automatically.

alertEndTimer = Timer.scheduledTimer(timeInterval: 10, 
                                     target: self, 
                                     selector: #selector(hideAlert),
                                     userInfo: nil,
                                     repeats: false)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download