How to stop NSTimer.scheduledTimerWithTimeInterval

You don’t have to use Selector:

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

Also, the timer passes itself to the selected method, so you can invalidate it inside the method if you need:

func updateTimer(timer: NSTimer) {
    timeLabel.text = String(Counter++)
    timer.invalidate()
}

Or if the timer is an instance variable:

myTimer.invalidate()
myTimer = nil

It’s a good thing to nil the instance variable timer after having invalidated it, it avoids further confusion if you need to create another timer with the same variable. Also, method names and variables should begin with a lowercase letter.

Screenshot to show the timer invalidated and set to nil.

screenshot

Update for Swift 2.2+

See https://stackoverflow.com/a/36160191/2227743 for the new #selector syntax replacing Selector().

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)