Dev0urCode
Dev0urCode

Reputation: 83

Timer counts instantly instead of respecting interval

Im trying to make a countdown timer. everything works fine except that my timer does not count at regular intervals (1sec); instead it counts all the way down instantly giving me 0 every time. did a lot of search without luck. All examples I could find show similar timeInterval parameter.

var timer = Timer()
var remainingTime = 120

@objc func timerCount () {
    if remainingTime > 0 {
        while remainingTime > 0 {
            remainingTime -= 1
            timerLabel.text = String(remainingTime)
            print(remainingTime)
        }
    } else {
        timer.invalidate()
    }
}

@IBAction func pauseButton(_ sender: Any) {
    timer.invalidate()
}

@IBAction func playButton(_ sender: Any) {
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.timerCount), userInfo: nil, repeats: true)
}

Upvotes: 0

Views: 46

Answers (2)

Shubham
Shubham

Reputation: 773

The reason your code is not working is that you have put an unnecessary while loop in your timerCount() method. You don't need to do this. Your timer will fire this method after each time interval. At very first call this while loop make your remainingTime to 0. This is why you are instantly getting 0 every time.

You just need to remove that while loop.

Upvotes: 1

BHAVIK
BHAVIK

Reputation: 899

Can You try like this

var timer = Timer()
var remainingTime = 120

@objc func timerCount () {
    let date = NSDate()

    let nowdate = UserDefaults.standard.object(forKey: "NowDate") as! Date


    let miniute = nowdate.timeIntervalSince(date as Date)

    print(Int(miniute))

    if (Int(miniute) == 0) {

        timer.invalidate()
         UserDefaults.standard.removeObject(forKey: "NowDate")

    } else {
        timerLabel.text = String(Int(miniute))
    }
}

@IBAction func pauseButton(_ sender: Any) {
    timer.invalidate()
    UserDefaults.standard.removeObject(forKey: "NowDate")

}

@IBAction func playButton(_ sender: Any) {
    let CurrentDate = NSDate()

    let NowDate = CurrentDate.addingTimeInterval(TimeInterval(remainingTime))

    UserDefaults.standard.set(NowDate, forKey: "NowDate")

    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.timerCount), userInfo: nil, repeats: true)
}

Upvotes: 0

Related Questions