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.
To start
To pause
To reset
'label' is the timer on output.
To stop it
To start it again
You can not resume the timer back. Instead of resuming - just create a new timer.
SWIFT3
Global Declaration
viewDidLoad
override func viewDidLoad() { super.viewDidLoad() BtnStart.tag = 0 }
Triggered IBACTION
Function that Handle The things
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:Even though the solutions exposed here are good, I thought an important insight was missing. Like a lot of people here explained, timer invalidate() and recreate is the best option. But one could argue that you could do something like this:
is easier to implement, but it will be less efficient.
For energy impact reasons, Apple promotes avoiding timers whenever possible and to prefer event notifications. If you really need to use a timer, you should implement pauses efficiently by invalidating the current timer. Read recommendations about Timer in the Apple Energy Efficiency Guide here: https://developer.apple.com/library/content/documentation/Performance/Conceptual/EnergyGuide-iOS/MinimizeTimerUse.html