NEW: Learn SwiftUI with my free YouTube video series! >>

How to make an action repeat using Timer

Swift version: 5.0

Paul Hudson    @twostraws   

Timers are a great way to run code on a repeating basis, and iOS has the Timer class to handle it for you. First, create a property of the type Timer?. For example:

var gameTimer: Timer?

You can then create that timer in somewhere like viewDidLoad() and tell it to execute every five seconds, like this:

gameTimer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(runTimedCode), userInfo: nil, repeats: true)

The runTimedCode selector means that the timer will call a method named runTimedCode() every five seconds until the timer is terminated, so you'll need to replace that method name with whatever you want to call – and don’t forget to mark it using @objc.

Important note: because your object has a property to store the timer, and the timer calls a method on the object, you have a strong reference cycle that means neither object can be freed. To fix this, make sure you invalidate the timer when you're done with it, such as when your view is about to disappear:


LEARN SWIFTUI FOR FREE I wrote a massive, free SwiftUI tutorial collection, and also have a growing list of free SwiftUI tutorials on YouTube – get started today!

Available from iOS 2.0 – see Hacking with Swift tutorial 20

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Average rating: 4.1/5

Click here to visit the Hacking with Swift store >>