Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a Timer work in Swift?

I am using a Timer in Swift and unsure of how it exactly works. I am trying to scan for 2 seconds, connect to a peripheral device, and then end scanning. I have the following code where connectToPeripheral , startScan, and endScan are functions in the same class.

    startScan()
Timer(timeInterval: 2, target: self, selector: #selector(connectToPeripheral), userInfo: nil, repeats: false)
    endScan()

How does the selector work in the timer? After the timer is called by the code, does the code only execute the selector and not call on whatever bit of code comes next or does it call on what comes next only after the selector finishes running? Basically, I'm asking what is the event cycle concerning Timers and its selector.

like image 928
Gerald Avatar asked Sep 07 '17 22:09

Gerald


People also ask

What is timer in Swift?

You can also use a timer to schedule a one time event for some time in the future. The main difference from the above example is that you use repeats: false instead of true . timer = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(delayedAction), userInfo: nil, repeats: false)

How do I add a delay in Swift?

To add a delay to your code we need to use GCD . GCD has a built in method called asyncAfter , which will allow us to run code after a given amount of time. In the above code, Before delay will be printed out first and after 2 seconds, Async after 2 seconds will be printed.

How do you create a 60s countdown timer that prints out the seconds remaining every second Swift?

Underneath the timerLabel outlet create the following variables: var seconds = 60 //This variable will hold a starting value of seconds. It could be any amount above 0. var timer = Timer() var isTimerRunning = false //This will be used to make sure only one timer is created at a time.


1 Answers

A Timer calls the method specified in its selector input argument after the time elapsed specified as the timeInterval. The Timer doesn't effect the life cycle of the rest of the code (except for the method specified in the selector of course), every other function is executed as normal.

See this minimal Playground example:

class TimerTest: NSObject {
    
    var timer:Timer?
    
    func scheduleTimer(_ timeInterval: TimeInterval){
        timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(TimerTest.timerCall), userInfo: nil, repeats: false)
    }
    
    func timerCall(){
        print("Timer executed")
    }
}

print("Code started")
TimerTest().scheduleTimer(2)
print("Execution continues as normal")

import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

Output:

print("Code started")

TimerTest().scheduleTimer(2)

print("Execution continues as normal")

like image 179
Dávid Pásztor Avatar answered Nov 25 '22 10:11

Dávid Pásztor