Show Menu

Looking to hire an app developer?

Submit your 30 day Job Listing for FREE

In this Tutorial I am going to show you how to create what is known as a Swift Timer. We will create a counter application. I am going to show you how to use NSTimer.

Jump to:

This Swift Timer Tutorial is a Swift 2 update to the already published

What is NSTimer?

The NSTimer class can be used to create swift timer objects in your iOS applications. Simply put – a swift timer. I’m sure you’ve all seen iOS applications that have a similar function to this. Ever wondered how they work? Wondering How NSTimer Works? Well, it works by waiting for a specific interval of time to elapse before it fires. Upon firing it will send a specified message to your swift app target object. For example you can tell your NSTimer object to send a message to a window with instructions to perform an update after a period of time has elapsed, or with this example update a label every second.

So now, are you wondering how to use NSTimer in Swift? Great. I’m about to show you in this swift timer tutorial.

Prepare the Xcode Project

Create a new Single View Application in your Xcode. Call it SwiftTimerTutorial.

Now, in the project Navigation, the left hand pane in Xcode, click Main.Storyboard. This will present to you a view controller where we will add elements for our Swift Timer.

The Elements we are going to use are:

  • Toolbar
  • Navigation Bar
  • Flexible Space Bar Button Item
  • Bar Button Item x 2
  • UILabel

All these elements can be found in the Xcode Object Library (Bottom right of Xcode). Simply search for the elements and drag them onto the ViewController.


Drag this element onto your View Controller and place it at the bottom, like so:

Swift Timer Toolbar

This Toolbar already has one item (button) on it called: Item. Select the button.

Now, in the Attributes Inspector, There is a drop down box next to the title: “System Item”. Click this drop down box and go through the options until you see play, and then select

Attributes Inspector for swift timer

You can now see that the “item” has changed to the play button:

Swift Timer Play Button

Flexible Space Bar Button Item

Now, drag one of these from the Object Library onto the toolbar and next to the play button, like so:

Flexible Space Bar item Swift Timer Tutorial

Bar Button Item (#1)

Drag one of these items onto your storyboard from the object library. Drag this to the right hand side of the Toolbar. Once you have done that, head back to the attributed inspector and change the “System Item” to pause. Just like we did with the “play” button:

This is going to be our Swift Timer Pause Button:

Swift Timer Pause Button

Navigation Bar

Drag one of these elements from the object Library to the top of your View Controller. Double click the work Title and change it to Swift Timer:

Navigation Bar Swift Timer

Bar Button Item (#2)

Drag another Bar button item onto your ViewController and position it to the right of the Swift Timer Navigation Bar. Double click the word Item and change it to Clear:

Swift Timer Clear Button


Finally, we are going to drag a UILabel onto the ViewController. Double Click the word Label and change it to 0. I have positioned this in the center and also changed the size using the attributes inspector.

That is now all the elements set up, so lets create a Swift Timer Application.

Link up elements

It is all fun and games adding elements to the ViewController but Xcode does not know what to do with them. It will display them when you run the swift timer project in the simulator but try clicking any of them. Nothing happens. So, no we need to make sure Xcode knows what we are going to do with them.

In your ViewController.swift file, inside the class Declaration Scope type:

@IBOutlet var countingLabel: UILabel!

@IBAction func startButton(sender: AnyObject) { }
@IBAction func pauseButton(sender: AnyObject) { }
@IBAction func clearButton(sender: AnyObject) { }

Head back over to your Main.Storyboard, We are now going to link up these Swift Timer Elements.

Click the “Clear” button, then hold down Control button on your keyboard and drag to the ViewController like so:

Link up elements

This will then display to you a dialogue with all the options. As you can see in the list there are the buttons that we just defined in code: Select clearButton:

swift timer select elements link

Go ahead and link up the rest of the buttons and the Label. You do not need to link up the navigation bar or the toolbar.

NSTimer in Swift

Now, go back to your Project Navigation and select the file ViewController.Swift. This is the file that controls what happens on the Main.Storyboard ViewController that we just edited. In this file is where we will define and program the NSTimer.

Define NSTimer

We first need to make an instance of NSTimer. We are going to do this by creating a variable called SwiftTimer which will equals NSTimer():

var SwiftTimer = NSTimer()

Now we need to define our counter. This is where we will display the swift timer number to the user. Create a variable called SwiftCounter of type integer and set it to an initial 0.

var SwiftCounter = 0

Now that we have added these variables, we can dynamically set them and do something with it.

You should see a ViewDidLoad func in your ViewController.Swift File. Inside this function we are going to get the value of the SwiftCounter variable that we just set, convert it to a string and then make it show in the label countingLabel.

countingLabel.text = String(SwiftCounter)

If you manually change the value of SwiftCounter and run your app. You should see now that the label has updated. That’s great, it means Xcode knows what the variables are and that they are supposed to update. Now let’s make it so that this Swift Timer app actually counts the number for us.

Start Swift Timer (NSTimer)

Inside the IBAction that we created for the Start Button, write:

@IBAction func startButton(sender: AnyObject) {
        SwiftTimer = NSTimer.scheduledTimerWithTimeInterval(TIME_INCREMENT, target:self, selector: Selector("FUNCTION"), userInfo: nil, repeats: BOOL)

What this code does is first assigns a new instance of NSTimer() to the Variable SwiftTimer that we initiated earlier. Inside this code there are a few things that we have written in capitals; TIME_INCREMENT, FUNCTION, BOOL. We are going to change these parameters. Here is what they do:

Parameter Usage
TIME_INCREMENT The number of seconds between firings of the timer. If seconds is less than or equal to 0.0, this method chooses the nonnegative value of 0.1 milliseconds instead. We are going to set this to 1.
FUNCTION A function that we will create that will be triggered on the time. We are going to call this updateCounter.
BOOL If YES, the timer will repeatedly reschedule itself until invalidated. If NO, the timer will be invalidated after it fires. We are going to set this to yes

Now that you know what we are going to do with these, change your code in the IBAction to reflect your desire:

@IBAction func startButton(sender: AnyObject) {
    SwiftTimer = NSTimer.scheduledTimerWithTimeInterval(1, target:self, selector: Selector("updateCounter"), userInfo: nil, repeats: true)

What we have done here is told the NSTimer() that we are going to run this every 1 second. On that second (When the Swift Timer fires) we are going to run a function called updateCounter, and we have also told it to repeat.

Now, we need to create the function that will be called when the Swift Timer app runs the NSTimer().

Out of the viewDidLoad function scope, create another function called updateCounter. Inside this function, we are going to tell swift that we want to get the value of SwiftCounter, add one to the value and then update the label:

func updateCounter() {
    countingLabel.text = String(SwiftCounter++)

Run the app and press the play button. The swift timer should start counting up, by one every second. This is the most basic use of NSTimer() in Swift.

Pause/Stop NSTimer

The NSTimer Class comes with a method called invalidate(). This method is the only way to remove a timer from an NSRunLoop object. The NSRunLoop object removes its strong reference to the timer, either just before the invalidate method returns or at some later point.

If it was configured with target and user info objects, the receiver removes its strong references to those objects as well.

You must send this message from the thread on which the timer was installed. If you send this message from another thread, the input source associated with the timer may not be removed from its run loop, which could prevent the thread from exiting properly.

In your IBAction that we created: pauseButton write:

@IBAction func pauseButton(sender: AnyObject) {

Run your app. Press the play button, watch the counter start running. Then press the pause button. Yay, you have just successfully started an Swift Timer and pause Swift Timer.

Clear/Reset the Swift Timer

In order to clear the Swift Timer we need to do several things:

  1. Stop NSTimer() from Firing
  2. Reset the SwiftCounter Variable
  3. Clear the countingLabel on the View

The above things must be done in that order.

They are all relatively simple things to do, and we are going to do this within the clearButton IBAction:

@IBAction func clearButton(sender: AnyObject) {
   SwiftCounter = 0
   countingLabel.text = String(SwiftCounter)


In this Swift Timer tutorial I have shown you how to create a new instance of NSTimer which fires every second and calls a function that updates an amount in a variable. It also then loads that amount to a UILabel on the ViewController effectively displaying a counting sequence to the user. This is what we refer to as a Swift Timer application.

Tl;Dr Download Files

To download the Swift Timer source files, please support us and let people know how awesome this tutorial is:

having issues?

We have a Questions and Answer section where you can ask your iOS Development questions to thousands of iOS Developers.

Ask Question

FREE Download!

Get your FREE Swift 2 Cheat Sheet and quick reference guide PDF download when you sign up to SwiftMonthly

Sharing is caring

If you enjoyed this tutorial, please help us and others by sharing using one of the social media buttons below.

iOS-Blog Admin Team

Written by:

We're here to help.