Home » Swift Timer

Swift Timer

While developing mobile applications, there are scenarios where we need to schedule some tasks to happen in the future. Swift provides a Timer class using which we can perform a task after a certain time interval.

In this article, we will discuss how we can use swift Timers to schedule the tasks. Also, we will discuss how we can use Repeating and Non-Repeating Timers.

The following code creates and run a Repeating Timer.

The above code requires an @objc method fireTimer() method defined in the same class.

Here, we have set the timer to be executed every 1 second. Therefore, the fireTimer() method will be called every 1 second. However, Swift allows us to define closures while creating a repeating timer, as shown below.

Both of the initializers are used to return the timer that is created. However, we can store the returned value in a property so that we can invalidate it later.

Creating non-repeating timer

The non-repeating timers are created if we want to run the code only once. For this purpose, we need to change the repeats attribute to false while creating the timer.

Ending a timer

We can end an existing timer by calling invalidate () method for the timer object. Consider the following example, which runs a code four times every 1 second and then invalidate the timer.

It prints the following output on the console.

"Timer fired"  "Timer fired"  "Timer fired"  "Timer fired"  

We have used a closure while creating a timer in the above example. We could have used the method approach here. However, invalidate the timer object in the method as shown below.

You may also like