Repository navigation
Using Timers
Configure a simple repeating timer as in the snippet below. After calling the scheduledTimer(timeInterval:target:selector:userInfo:repeats:) method, the timer is immediately scheduled and will call the method at the time interval.
Declare and implement the method that you want to be called when the timer fires. You can name this method whatever you want, just pass the name of the method to the timer when you create it. Apple's documentation says the method should take one argument: the timer passes itself in, so the method can, for example, call invalidate() on it.
@objc func onTimer(_ timer: Timer) {
// Add code to be run periodically
}- (void)onTimer:(NSTimer *)timer {
// Add code to be run periodically
}For example, to schedule the onTimer method to be called every 5 seconds, use the code below. If you want the timer to fire every 100ms, just use 0.1 for the time interval.
Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(onTimer(_:)), userInfo: nil, repeats: true)[NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(onTimer:) userInfo:nil repeats:true];Since iOS 10, Swift can also use the closure-based Timer.scheduledTimer(withTimeInterval:repeats:block:) variant, which avoids the target/selector boilerplate:
Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { timer in
// Add code to be run periodically
}To stop a repeating timer, keep a reference to the returned Timer and call invalidate() on it. A repeating timer keeps firing until it is invalidated, and the target/selector version keeps a strong reference to its target until then, so a timer that targets self keeps self from being deallocated until you invalidate it.