Skip to content

Commit

Permalink
Merge pull request #252 from ankurp/debounce
Browse files Browse the repository at this point in the history
Adding debounce and delay functions
  • Loading branch information
ankurp authored Mar 26, 2017
2 parents c0dd3c0 + 89fb200 commit df57cb4
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
27 changes: 27 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,33 @@ $.cycle([1, 2, 3], 2) {
123123
```

### delay - `$.delay`

Delays the execution of a function by the specified DispatchTimeInterval

```swift
$.delay(by: .seconds(2)) {
print("Hello delayed by 2 seconds")
}
=> "Hello delayed by 2 seconds"
```

### debounce - `$.debounce`

Debounce a function such that the function is only invoked once no matter how many times it is called within the delayBy interval

```swift
let printQueue = $.debounce(delayBy: .seconds(1)) {
print("Hello Queue!")
}
for _ in 0...9 {
printQueue()
}
$.delay(by: .seconds(2), printQueue)
=> "Hello Queue!"
=> "Hello Queue!"
```

### difference - `$.difference`

Creates an array excluding all values of the provided arrays
Expand Down
25 changes: 25 additions & 0 deletions Sources/Dollar.swift
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,31 @@ open class $ {
}
}

/// Delays the execution of a function by the specified DispatchTimeInterval
///
/// - parameter by: interval to delay the execution of the function by
/// - parameter queue: Queue to run the function on. Defaults to main queue
/// - parameter function: function to execute
open class func delay(by interval: DispatchTimeInterval, queue: DispatchQueue = .main, _ function: @escaping () -> Void) {
queue.asyncAfter(deadline: .now() + interval, execute: function)
}

/// Debounce a function such that the function is only invoked once no matter how many times
/// it is called within the delayBy interval
///
/// - parameter delayBy: interval to delay the execution of the function by
/// - parameter queue: Queue to run the function on. Defaults to main queue
/// - parameter function: function to execute
/// - returns: Function that is debounced and will only invoke once within the delayBy interval
open class func debounce(delayBy: DispatchTimeInterval, queue: DispatchQueue = .main, _ function: @escaping (() -> Void)) -> () -> Void {
var currentWorkItem: DispatchWorkItem?
return {
currentWorkItem?.cancel()
currentWorkItem = DispatchWorkItem { function() }
queue.asyncAfter(deadline: .now() + delayBy, execute: currentWorkItem!)
}
}

/// Creates an array excluding all values of the provided arrays in order
///
/// - parameter arrays: The arrays to difference between.
Expand Down

0 comments on commit df57cb4

Please sign in to comment.