Swift
Timer
NSTimer
iOS development
Swift programming

How can I use Timer formerly NSTimer in Swift?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Understanding Timer in Swift

In Swift, the Timer class (formerly known as NSTimer) is a powerful utility that allows developers to schedule the execution of code at specified intervals. Whether you need to update a countdown, refresh UI components, or perform periodic checks, Timer can help manage timed tasks efficiently. This article will delve into the mechanics of Timer, how to use it, and some best practices to follow.

How Timer Works

A Timer object waits until a certain time interval has elapsed and then fires, executing a specified selector or block. When using Timer, it's important to understand its lifecycle and the run-loop mechanism it uses. Timer is generally of two types:

  1. Repeating Timer: Executes repeatedly at specified intervals.
  2. Non-Repeating Timer: Fires once after a certain delay.

Creating a Timer

In Swift, you can create a timer using the scheduledTimer methods or the Timer initializer:

swift
1// Using scheduledTimer
2let timer = Timer.scheduledTimer(timeInterval: 1.0,
3                                 target: self,
4                                 selector: #selector(timerAction),
5                                 userInfo: nil,
6                                 repeats: true)
7
8// Using Timer initializer
9let timer = Timer(timeInterval: 1.0,
10                  target: self,
11                  selector: #selector(timerAction),
12                  userInfo: nil,
13                  repeats: true)
14
15RunLoop.main.add(timer, forMode: .common)

Timer Methods

  • timeInterval: The time interval between timer fires, specified in seconds.
  • target: The object whose selector will be called when the timer fires.
  • selector: The method to be called.
  • userInfo: An optional dictionary to pass data to the selector.
  • repeats: A Boolean to determine if the timer should repeat.

Using Timer in Practice

Example: Countdown Timer

To create a countdown timer that decrements a label value every second:

swift
1import UIKit
2
3class ViewController: UIViewController {
4    var timer: Timer?
5    var counter = 10
6
7    override func viewDidLoad() {
8        super.viewDidLoad()
9        startTimer()
10    }
11  
12    func startTimer() {
13        timer = Timer.scheduledTimer(timeInterval: 1.0,
14                                     target: self,
15                                     selector: #selector(updateTimerLabel),
16                                     userInfo: nil,
17                                     repeats: true)
18    }
19
20    @objc func updateTimerLabel() {
21        if counter > 0 {
22            print("Counter: \(counter)")
23            counter -= 1
24        } else {
25            timer?.invalidate()
26            print("Timer finished!")
27        }
28    }
29}

Example: Using Timer with Closures

Alternatively, use closures for cleaner code without selectors:

swift
1let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
2    // Code to execute
3    print("Timer fired!")
4}

Best Practices

  • Invalidate Timers: Always invalidate a timer when it's no longer needed. Failing to do so can lead to memory leaks and unexpected behaviors.
swift
  timer?.invalidate()
  timer = nil
  • Manage RunLoop Modes: When adding a timer to a run loop, consider the mode. Using .common ensures the timer fires during tracking events like UI interactions.
  • Avoid Retain Cycles: Prevent strong reference cycles by using [weak self] in closures:
swift
  timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] timer in
      self?.updateFunction()
  }

Challenges and Considerations

  • Run Loop Dependency: Timer requires a run loop to function. It's unsuitable for tasks when the run loop isn't spinning.
  • Accuracy: Timer provides decent accuracy, but deviations can occur due to system constraints. Use CADisplayLink or GCD for high-precision tasks.
  • Background Execution: Timer doesn't fire in the background unless your app requests additional time or implements specific background modes.

Summary Table

Key FeatureDescription
Timer TypesRepeating & Non-Repeating
Creation MethodsscheduledTimer, Timer(timeInterval:)
Selector-based ExecutionUse selector to specify the method
Closure-based ExecutionAlternatively, schedule with a closure
Run Loop IntegrationUse RunLoop to specify a mode
Invalidationtimer?.invalidate() to stop a timer
Avoiding Retain CyclesUse [weak self] in closures
Background ConstraintsTimer pauses in the background without specific configurations

Timer in Swift is a versatile class, suitable for scheduling tasks with ease. By following best practices and understanding its limitations, you can leverage Timer to enhance your application's functionality efficiently.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.