Skip to main content

Debounce in Swift

swift

Prevent rapid-fire function calls using a lightweight debounce wrapper.

Useful when you need to delay execution until the user stops typing or scrolling.

func debounce(delay: TimeInterval, action: @escaping () -> Void) -> () -> Void {
    var timer: Timer?
    return {
        timer?.invalidate()
        timer = Timer.scheduledTimer(withTimeInterval: delay, repeats: false) { _ in
            action()
        }
    }
}

// Usage
let debouncedSearch = debounce(delay: 0.3) {
    performSearch()
}