简体   繁体   中英

NSTimer work only the first time (Swift)

I don't know why my timer working only the first time, this is the code: When I press "timergo" button it work but when it finish and repress the button it doesn't work.

@IBAction func timergo(sender: AnyObject) {      
          startTimer()
    }

    var timer:NSTimer!
    var timerVal:Int = 5

    func startTimer()
    {       
        timer = NSTimer.scheduledTimerWithTimeInterval(1.0
            , target: self, selector: Selector("updateTimer:"), userInfo: nil, repeats: true)
    }

    func updateTimer(dt:NSTimer)
    {
        timerVal--

        if timerVal==0{               
            println("FINISH")
        }else if timerVal < 0{
            timer.invalidate()
            //Stop
        } else{
           justTime.text = String(timerVal)
            println("\(timerVal)")
        }   
    }

You need to reset the timerVal when you press the button. When you start it for the second time, timerVal is still < 0 so it directly goes to invalidate.

timerVal is 5 when you push the button the first time; it is less than 0 the second time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM