Search code examples
swifttimercycle

Timer.scheduled(); I cannot stop variable++ cycle


enter image description here

How i can stop a cycle?

Code 1

 @objc func dismissImageView() {
    timer1 = Timer()
    timer1 = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(timerWillDisappear), userInfo: nil, repeats: true)
    
}

Code 2

   **When i touch on myView - timer's beginning and don't stop!**
@objc func timerWillDisappear() {
    if repeatsVar != 1.0 {
        repeatsVar! += 0.01
    } 
}

Code 3

else if repeatsVar == 1.0 { **This if doesn't work!!!**
            timer1.invalidate()
            timer1 = nil
            repeatsVar! -= 1
            self.view.removeFromSuperview()
        }

Solution

  • Floating point numbers have some error to them. You likely won't get a value that is exactly 1.0. Since you stop as soon as you value gets to 1.0, why not check to see if it is less than 1.0 instead?

    @objc func timerWillDisappear() {
        if repeatsVar < 1.0 {
            repeatsVar += 0.01
        } else 
            timer1.invalidate()
            timer1 = nil
            repeatsVar = 0
            self.view.removeFromSuperview()
        }
    }
    

    Also note that your dismissImageView() method should not create an empty timer and then a scheduled timer:

    @objc func dismissImageView() {
        //timer1 = Timer() <- Get rid of this line.
        timer1 = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(timerWillDisappear), userInfo: nil, repeats: true)
    }