How can I make a function execute every second in swift?
You can use one like this:
var timer = NSTimer()override func viewDidLoad() { scheduledTimerWithTimeInterval()}func scheduledTimerWithTimeInterval(){ // Scheduling timer to Call the function "updateCounting" with the interval of 1 seconds timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateCounting"), userInfo: nil, repeats: true)} func updateCounting(){ NSLog("counting..")}
Swift 3:
var timer = Timer()override func viewDidLoad() { // Use for the app's interface scheduledTimerWithTimeInterval()}override func didMove(to view: SKView) { // As part of a game scheduledTimerWithTimeInterval()}func scheduledTimerWithTimeInterval(){ // Scheduling timer to Call the function "updateCounting" with the interval of 1 seconds timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.updateCounting), userInfo: nil, repeats: true)}@objc func updateCounting(){ NSLog("counting..")}
Swift 5:
Note: this solution is compatible with iOS 10.0+.
// If needing to check for iOS compatibility use// if #available(iOS 10.0, *) {code}var timer = Timer()override func viewDidLoad() { self.timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { _ in updateCounting() })}func updateCounting(){ print("counting...")}
You can then invalidate (stop) the timer using:
timer.invalidate()
There is something called NSTimer in swift which could solve your problem. I have given an example like how you can use it. Just customise it for your purpose.
var timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("yourMethodToCall"), userInfo: nil, repeats: true)
Add this line to the place where you need to call your function repeatedly.
- The
1.0
refers to 1 second. - Change the
selector
to call yourMethodName repeats
is set totrue
to call that function every second.
Try this out and let me know if your are stuck somewhere. Thanks.
Swift 3
find this solution it worked for me
weak var timer: Timer?var timerDispatchSourceTimer : DispatchSourceTimer?func startTimer() { if #available(iOS 10.0, *) { timer = Timer.scheduledTimer(withTimeInterval: 3, repeats: true) { [weak self] _ in // do something here } } else { // Fallback on earlier versions timerDispatchSourceTimer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.main) timerDispatchSourceTimer?.scheduleRepeating(deadline: .now(), interval: .seconds(60)) timerDispatchSourceTimer?.setEventHandler{ // do something here } timerDispatchSourceTimer?.resume() }}func stopTimer() { timer?.invalidate() //timerDispatchSourceTimer?.suspend() // if you want to suspend timer timerDispatchSourceTimer?.cancel()}// if appropriate, make sure to stop your timer in `deinit`deinit { stopTimer()}