How to Create a Timer in Swift?

Timers are essential for scheduling tasks, updates, and animations in your Swift applications. Whether you want to periodically update a user interface, fetch data from a server, or perform other time-based operations, Swift provides a convenient way to create timers. In this article, we’ll explore how to create timers in Swift, covering both the old NSTimer and the newer Timer class introduced in Swift.

Using NSTimer (Objective-C)

NSTimer is the old Objective-C way of creating timers and can still be used in Swift. Here’s how to create and use an NSTimer in Swift:

import Foundation

let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)

@objc func updateTimer() {
    // Your timer's action code here
}

In this example, we schedule a timer to call the updateTimer function every 1 second. The updateTimer function can contain the code you want to execute on each timer tick.

Using Timer (Swift)

Swift introduced the Timer class, which is a more Swifty and convenient way to create timers. Here’s how to create a timer using the Timer class:

import Foundation

let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
    // Your timer's action code here
}

The Timer class allows you to provide a closure directly, making your code cleaner and more readable.

Stopping a Timer

To stop a timer, you can call the invalidate method on the timer instance:

timer.invalidate()

Timer on the Main Thread

Timers execute on the thread they are created on. To ensure your timer executes on the main thread (useful for UI updates), create it within a DispatchQueue.main.async block:

DispatchQueue.main.async {
    let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
        // Your timer's action code here
    }
}

Hope this helps!!!

A pat on the back !!