Search code examples
iosswiftnstimer

How to stop NSTimer with another NSTimer?


Note: I am using swift for this project.

I am currently working on my first project and I am trying to stop (invalidate) an NSTimer if a button was not pressed after a certain amount of time. I have found other ways of stopping my NSTimer but none saying how to stop it after a certain amount of time, with that time being reset if the button actually is pressed. Read everything to understand more clearly.

Here is my code now;

@IBOutlet var Text: UILabel!
var timer: NSTimer!
var countdown: Int = 0

@IBAction func StartGame(sender: AnyObject) {
self.countdown = 20
self.timer = NSTimer.scheduledTimerWithTimeInterval(1.5, target: self, selector: "updateCountdown", userInfo: nil, repeats: true)
}

func updateCountdown() {

    self.countdown--

    if self.countdown == 0 {
        self.timer.invalidate()
        self.timer = nil
    }

    let texts: NSArray = ["Test", "Testing"]
    let range: UInt32 = UInt32(texts.count)
    let randomNumber = Int(arc4random_uniform(range))
    let textstring = texts.objectAtIndex(randomNumber)

    self.ColorText.text = textstring as? String
}

@IBAction func PlayerbuttonPRESSED(sender: AnyObject) {
if Text.text == "Test" {
//Something happens
}
if Text.text == "Testing" {
//Something happens 
}

What I am dying to know is how I make something else happen if the button was not pressed before ColorText.text was changed! (If the button was not pressed before changing the text after 1.5 seconds).

Ps. Sorry for the long code, I think it is necessary. :-)


Solution

  • There are different ways of doing this. One way, you could set bool value to true when the button is pressed then in updateCountdown check to the boolean.

    For example:

    func updateCountdown() {
    
         self.countdown--
    
        if self.countdown == 0 && YOUR_BUTTON_BOOL {
            self.timer.invalidate()
            self.timer = nil
        }  
    
        let texts: NSArray = ["Test", "Testing"]
        let range: UInt32 = UInt32(texts.count)
        let randomNumber = Int(arc4random_uniform(range))
        let textstring = texts.objectAtIndex(randomNumber)
    
        self.ColorText.text = textstring as? String
    }
    

    However, using NSTimer in this fashion where you have it trigger in a short period of time like 1.5 seconds can become inaccurate. After the timer triggers 20 times the time past will be greater than 30 seconds. If accuracy is important you might be better off setting a second timer for 30 seconds. If the button is pressed it invalidates the 30 second timer if the 30 second timer fires it invalidates the 1.5 second timer.