Debouncer Actor

Actor-based debouncing and throttling for rate-limiting async operations.

← Back
Language: swift | Tags: debounce throttle actor concurrency
/// Debounce actor for rate-limiting operations
actor Debouncer {
    private var task: Task<Void, Never>?
    private let duration: Duration

    init(duration: Duration = .milliseconds(300)) {
        self.duration = duration
    }

    func debounce(operation: @escaping @Sendable () async -> Void) {
        task?.cancel()
        task = Task {
            try? await Task.sleep(for: duration)
            guard !Task.isCancelled else { return }
            await operation()
        }
    }
}

/// Throttle actor - executes at most once per interval
actor Throttler {
    private var lastExecutionTime: Date?
    private let interval: TimeInterval

    init(interval: TimeInterval) {
        self.interval = interval
    }

    func throttle(operation: @escaping @Sendable () async -> Void) async {
        let now = Date()
        if let lastTime = lastExecutionTime,
           now.timeIntervalSince(lastTime) < interval {
            return
        }
        lastExecutionTime = now
        await operation()
    }
}

// Usage:
// let debouncer = Debouncer(duration: .milliseconds(500))
// await debouncer.debounce { await searchAPI(query) }