Timer

Based on a time interval, we can trigger some action repeatedly.

// TODO: Can we trigger once??

struct PlaygroundView: View {

    let timer = Timer.publish(
        every: 1,       // Second
        tolerance: 0.1, // Gives tolerance so that SwiftUI makes optimization
        on: .main,      // Main Thread
        in: .common     // Common Loop
    ).autoconnect()
    
    @State var counter = 0
    
    var body: some View {
        
        Text(String(counter))
            .font(.largeTitle)
            .onReceive(timer) { (time) in
                self.counter += 1
                if self.counter == 7 {
                    // Cancels Timer
                    self.timer.upstream.connect().cancel()
                }
            }
            
    }
    
}

Last updated