How to stop NSTimer.scheduledTimerWithTimeInterval

Erik Auranaune picture Erik Auranaune · Apr 20, 2015 · Viewed 47.4k times · Source

How do i stop my timer from running? Not like a pause, but a stop.

import UIKit

class LastManStandingViewController: UIViewController {    

@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var timeTextbox: UITextField!
@IBOutlet weak var startButton: UIButton!
@IBOutlet weak var stopButton: UIButton!

var myCounter = 0
var myTimer : NSTimer = NSTimer()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    timeLabel.text = String(myCounter)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func startTimer(){
    myTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateTimer"), userInfo: nil, repeats: true)
    println("func startTimer")
}

func stopTimer(){
    myTimer.invalidate()
    myCounter = 0
    timeLabel.text = String(myCounter)
    println("func stopTimer")
}

func updateTimer(){
    timeLabel.text = String(myCounter++)
    println("func updateTimer")
}
@IBAction func startButton(sender: AnyObject) {
    startTimer()
}
@IBAction func stopButton(sender: AnyObject) {
    stopTimer()
}

}

I can start the timer, but when i press the Stop button, it reset itself, and starts counting again. It doesn't stop.

Made it work. Something was buggy with my project! Fixed it by removing the button and re-adding them. Looks like i had a duplicate or something.

Answer

Eric Aya picture Eric Aya · Apr 20, 2015

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