Timers in Swift

A timer sends a message to an object after a certain amount of time passes. Start by declaring a variable for the timer.

Starting a Timer

Call the scheduledTimer method to start a timer. The scheduledTimer method takes the following arguments:

  • A time interval for how often the timer fires, specified in seconds.
  • Target, which is the object that receives the message from the timer.
  • Selector, which is the function the target should run after receiving the message.
  • UserInfo, which is optional additional information you can send.
  • Repeats, which indicates whether the timer runs once or repeats.

The following code starts a timer to autosave data every 30 seconds:

The function for the selector needs @objc at the start of the declaration.

Stopping a Timer

Call the invalidate method to stop a timer. The following code stops a timer: