Home > database >  Create a timer that pauses the code's flow Swift
Create a timer that pauses the code's flow Swift

Time:10-17

Does a timer like let timer = Timer.scheduledTimer(timeInterval: 10.0, target: self, selector: #selector(fireTimer), userInfo: nil, repeats: false) actually stops the code for 10 seconds? Or will the code behind keeps running? I need a timer that could pause the code's flow for 10 seconds, and I don't want to use sleep or a closure! How can I implement this? Thanks.

CodePudding user response:

You can probably use a Bool and the Timer in combination.

Take 2 Timers.

Timer1 - would at equal intervals call a method which internally checks the flag and would perform / not perform the action.

let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(fireTimer), userInfo: nil, repeats: true)

func fireTimer() {
   if self.blockCode { return }
   // your code here
}

Timer2 - would toggle the flag after a given set time, lets say 10 seconds.

self.blockCode = true
DispatchQueue.main.asyncAfter(deadline: .now()   10.0) {
    self?.blockCode = false
}

This would make you stop a code from execution for a fixed set of time without actually freezing the app like sleep would do.

Hope this helps.

  • Related