How can I pause and resume NSTimer.scheduledTimerWithTimeInterval in swift? How can I pause and resume NSTimer.scheduledTimerWithTimeInterval in swift? swift swift

How can I pause and resume NSTimer.scheduledTimerWithTimeInterval in swift?


You need to invalidate it and recreate it. You can then use an isPaused bool to keep track of the state if you have the same button to pause and resume the timer:

var isPaused = truevar timer = NSTimer()    @IBAction func pauseResume(sender: AnyObject) {         if isPaused{        timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("somAction"), userInfo: nil, repeats: true)        isPaused = false    } else {        timer.invalidate()        isPaused = true    }}


To start

timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.action), userInfo: nil, repeats: true)

To pause

timer.invalidate()

To reset

time += 1label.text = String(time)

'label' is the timer on output.


To Start:

timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("updateView"), userInfo: nil, repeats: true)

To Resume:

timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("updateView"), userInfo: nil, repeats: true)

To Pause:

timer.invalidate

This worked for me. The trick is that do not look for something like "timer.resume" or "timer.validate". Just use "the same code for starting a timer" to resume it after the pause.