How does one create a while loop that checks it's condition every second?
maybe something like this:
while (isConditionSatisfied){
// wait for 1 second and than check again
}
EDIT: The system calls this function bannerViewDidLoadAd
at random times. If it calls it at inappropriate time(condition is unsatisfied-my app is performing some other animation), I would like to defer its implementation(just an UIView animation) until the condition is satisfied(my app has finished animating, now the implementation should be executed). I was thinking I could check the condition in a while loop every second, but as you guys said..this is a bad idea.
Using while loop like this will create an infinite loop actually. You should use Timer().
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.loop), userInfo: nil, repeats: true)
And then
@objc
func loop() {
if yourCondition {
// your code here
timer.invalidate()
}
}
Make sure you declare timer with your other variable declarations, so it can be invalidated once your condition has been met:
var timer: Timer!
Swift loop with interval
iOS 10
Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { (timer) in
if someCondition {
timer.invalidate()
}
}
*withTimeInterval
- number of seconds
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With