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()

Leave a Comment