Swift: How to invalidate a timer if the timer starts from a function?
If you need to be able to stop the timer at any point in time, make it an instance variable.
If you will only ever need to stop it in the method it is called, you can have that method accept an NSTimer
argument. The timer calling the method will pass itself in.
class ClassWithTimer {
var timer = NSTimer()
func startTimer() {
self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "timerTick:", userInfo: nil, repeats: true)
}
@objc func timerTick(timer: NSTimer) {
println("timer has ticked")
}
}
With this set up, we can now either call self.timer.invalidate()
or, within timerTick
, we can call timer.invalidate()
(which refers to the timer which called the method).
Invalidate Timer from Function in Swift
Declare your timer as a class variable:
var checkStateTimer: NSTimer!
And then set it in viewDidLoad():
func viewDidLoad() {
super.viewDidLoad()
checkStateTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "callCheckState:", userInfo: nil, repeats: true)
}
Then in your function invalidate the timer:
func someFunction() {
checkStateTimer.invalidate()
}
Swift: How do I invalidate all running timers?
You can subclass Timer
and have a shared instance which has stores all the timers currently in use. You have to use this CustomTimer
instead of Timer
whenever you need a timer.
class CustomTimer: Timer {
static var sharedTimers: [CustomTimer] = []
static func invalidateAllTimers() {
for timer in CustomTimer.sharedTimers {
timer.invalidate()
}
}
// Use appropriate initializer and super calls.
init() {
CustomTimer.sharedTimers.append(self)
}
deinit {
CustomTimer.sharedTimers.removeAll { (timer) -> Bool in
return timer === self
}
}
}
Now you can invalidate all the timers by using the invalidateAllTimers
method.
CustomTimer.invalidateAllTimers()
swift invalidate timer in function
the problem is that each time you're accessing GameClock, you are creating a new instance of it - so the instance that you're stopping is not the one that you created.
You can keep all of the functionality in the GameClock
class, but you will need to define a variable in ViewController
to access it.
class ViewController: UIViewController {
var gameClock = Gameclock()
and then in your startstopPushed
method make these changes
if startstopPushed == false {
//Gameclock().startGameclock()
gameClock.startGameclock()
startstop.setImage(UIImage(named: "stop.png"), forState: UIControlState.Normal)
startstopPushed = true
}
else
{
//Gameclock().stopGameclock()
gameClock.stopGameclock()
startstop.setImage(UIImage(named: "start.png"), forState: UIControlState.Normal)
startstopPushed = false
}
How to invalidate timer without setting variable
You need to still call timer.invalidate()
but here timer
is reference to the block of the Timer
.
Timer.scheduledTimer(withTimeInterval: 5, repeats: true, block:
{
timer in //This is object that you need to use
//do stuff
//when something happens
timer.invalidate()
})
stop the timer which is executed after button click
Solution 1 : make a variable
var timerCount:Timer!
@IBAction func onClickAnimate(_ sender: Any) {
timerCount = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)
}
@objc func updateCounter(){
if timer > 0 {
timer -= 1
}
if timer == 0 {
timer = 5
timerCount.invalidate()
}
}
Solution 2 : use block
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timerCount in
if self.timer > 0 {
self.timer -= 1
}
else
if self.timer == 0 {
self.timer = 5
timerCount.invalidate()
}
}
Can't invalidate timer swift
You never actually assign a new value to your variables. The timers you create are not saved anywhere, therefore you cannot invalidate them.
I would recommend the following changes:
var timer: Timer? {
didSet {
oldValue?.invalidate()
}
}
var timer2: Timer? {
didSet {
oldValue?.invalidate()
}
}
This will make sure the previous timer is always invalidated when assigning a new one. You can then invalidate using timer = nil
or timer2 = nil
.
Also, you should return the timer from your method:
func timerWithDifferentIntervals(interval: TimeInterval, target: Any, selector: Selector, userInfo: Any?, repeats: Bool) -> Timer {
return Timer.scheduledTimer(timeInterval: interval, target: target, selector: selector, userInfo: userInfo, repeats: repeats)
}
and use it in following way:
timer = timerWithDifferentIntervals(interval: 1, target: self, selector: #selector(handle1), userInfo: nil, repeats: true)
Although the method does basically nothing now, so there is no need for it
Related Topics
How to Display Mtkview with Rgba16Float Mtlpixelformat
How to Change the Appearance of the Datepicker in the Swiftui Framework to Only Months and Years
Tabview, Tabitem: Running Code on Selection or Adding an Ontapgesture
Undefined Symbol Objc_Class_$ When Creating iOS Framework
Swift Issue in Passing Variable Number of Parameters
Example for Drag and Drop Inside Nscollectionview
How to Set Up Multiple Combine Timer Publishers
Why Won't My Collection View Cells Display in the iPhone Simulator
Generate Labels and Align in Middle
How to Use a Switch Statement with a Nested Enum
How to Run the Simulator the Operation Couldn't Be Completed. (Launchserviceserror Error 0.)
Cannot Preview This File, App May Have Crashed -- Occurs When Inputting Specific Line of Code
C++ Dylib in Swift Project - Undefined Symbols for Function Exposed in Dylib
How to Create Lazy Combinations
How to Parse JSON in JSON with Swiftyjson
Get Images from Document Directory Not File Path Swift 3