Search code examples
swiftcountdowndiscount

How to decrease a value constantly when countdown is started?


I want to merge something with this code. My goal is to add a price value in a label which is decreasing constantly ever second when countdown is started. For ex: CurrentPrice - DiscountPerSecond on first second then CurrentPrice - DiscountPerSecond*2 on second etc.. until countdown is finished.

var timerCounter:NSTimeInterval!

   func updateTime(interval: NSTimeInterval) -> String {

        let interval = Int(interval)

        let seconds = interval % 60

        let minutes = (interval / 60) % 60

        let hours =  interval / 3600


        return String(format: "%02d:%02d:%02d", hours, minutes, seconds)

    }




    func startTimer(hour:Int) {
        timerCounter = NSTimeInterval(hour * 60 * 60)
        let aSelector : Selector = "onTimer:"
        NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: aSelector, userInfo: nil, repeats: true)


    }


    func onTimer(timer:NSTimer!) {
        countdownShow.text = updateTime(timerCounter)
        timerCounter!--

        if (timerCounter == 0) {
            timer.invalidate()
            countdownShow.text = "Event Closed!"
        }
    }

Solution

  • A few notes:

    1. Instead of counting down from a time interval, you should store a fixed end date and calculate time intervals from the current time as needed.
    2. You should calculate discounts based on a proportion of a maximum discount divided by the proportion of time remaining. (i.e. price = listPrice - (maximumDiscount * proportionOfTimeElapsed))
    3. You should use NSDateComponentsFormatter to format the remaining time.