Eric Lee
Eric Lee

Reputation: 710

Swift how to prevent multiple NSTimer.scheduledTimerWithTimeInterval

I have been making a stopwatch.

and start, stop, and pause action work great.

However, When I click start action double times which is

time = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("result"), userInfo: nil, repeats: true)

this action start again and the time run faster!

how do i prevent the action?

Thanks in advance!!!

Upvotes: 2

Views: 1170

Answers (2)

Eric Lee
Eric Lee

Reputation: 710

I found a simple answer!!!

However, The answer above is simpler than an answer I found.

What I found was

I just need to declare a variable let say

var isStop = true

then when

Timer.scheduledTimerWithTimeInterval()

run I need to put

isStop = false

and also every pause and stop action I need to put

isStop = true

Thanks everyone for reminding me of thinking different!!

Upvotes: 0

Twitter khuong291
Twitter khuong291

Reputation: 11672

You need to declare a variable on the top of your class:

 var timer = NSTimer()

then you assign this timer variable in your start button, like so:

@IBAction func startTimerButtonTapped(sender: UIButton) {
   time = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("result"), userInfo: nil, repeats: true)
}

whenever you want to stop this timer, you need to invalidate it, like so:

timer.invalidate()

If you want to click the start button two more time, you need to invalidate it first before schedule it:

@IBAction func startTimerButtonTapped(sender: UIButton) {
       timer.invalidate()
       time = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("result"), userInfo: nil, repeats: true)
    }

Hope this will help you.

Upvotes: 3

Related Questions