How to stop NSTimer.scheduledTimerWithTimeInterval How to stop NSTimer.scheduledTimerWithTimeInterval ios ios

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


you can use this when some condition is met and you want to stop timer:

Timer.invalidate()

Here is simple example :

func UpdateTimer(){    timeLabel.text = String(Counter++)    if timeLabel.text == String("5") {        Timer.invalidate()    }}

this will stop timer.

You can modify it as per your need.


As pre Swift 2.2

let printTimer = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: #selector(printDescription), userInfo: nil, repeats: true)func printDescription() {    print("Print timer will print every after 2.0 seconds")}

Print timer will print every after 2.0 seconds