Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm developing a game and I want to create a pause menu. Here is my code:

self.view?.paused = true 

but NSTimer.scheduledTimerWithTimeInterval still running...

 for var i=0; i < rocketCount; i++ {     var a: NSTimeInterval = 1     ii += a     delaysShow = 2.0 + ((stimulus + interStimulus) * ii)            var time3 = NSTimer.scheduledTimerWithTimeInterval(delaysShow!, target: self, selector: Selector("showRocket:"), userInfo: rocketid[i], repeats: false)  } 

I want time3 to pause the timer when player click pause menu and continue run the timer when player come back to the game, but how can I pause NSTimer.scheduledTimerWithTimeInterval? help me please.

like image 871
Pandu Arif Septian Avatar asked Apr 02 '15 06:04

Pandu Arif Septian


2 Answers

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 = true var 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     } } 
like image 192
jonnie Avatar answered Sep 21 '22 18:09

jonnie


To start

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

To pause

timer.invalidate() 

To reset

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

'label' is the timer on output.

like image 42
Rashid KC Avatar answered Sep 21 '22 18:09

Rashid KC