Skip to content

Commit

Permalink
Add Debouncer type with delay function
Browse files Browse the repository at this point in the history
  • Loading branch information
Jeehut committed Oct 17, 2023
1 parent 985a5fe commit a44f5b3
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions Sources/HandySwift/Types/Debouncer.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import Foundation

/// A class for delaying and debouncing operations.
public final class Debouncer {
private var timerByID: [String: Timer] = [:]

/// Initializes a new instance of the `Debouncer` class.
public init() {}

/// Delays operations and cancels all but the last one when the same `id` is provided.
///
/// - Parameters:
/// - duration: The time duration for the delay.
/// - id: An optional identifier to distinguish different delays (default is "default").
/// - operation: The operation to be delayed and executed.
///
/// This version of `delay` uses a `Duration` to specify the delay time.
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
public func delay(for duration: Duration, id: String = "default", operation: @escaping () -> Void) {
self.timerByID[id]?.invalidate()
self.timerByID[id] = Timer.scheduledTimer(withTimeInterval: duration.timeInterval, repeats: false) { _ in
operation()
}
}

/// Delays operations and cancels all but the last one when the same `id` is provided.
///
/// - Parameters:
/// - interval: The time interval for the delay.
/// - id: An optional identifier to distinguish different delays (default is "default").
/// - operation: The operation to be delayed and executed.
///
/// This version of `delay` uses a `TimeInterval` to specify the delay time.
public func delay(for interval: TimeInterval, id: String = "default", operation: @escaping () -> Void) {
self.timerByID[id]?.invalidate()
self.timerByID[id] = Timer.scheduledTimer(withTimeInterval: interval, repeats: false) { _ in
operation()
}
}
}

0 comments on commit a44f5b3

Please sign in to comment.