Skip to content

Instantly share code, notes, and snippets.

@blork
Last active March 20, 2019 14:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blork/8c45a2b99571719c0f55b39d2ac35434 to your computer and use it in GitHub Desktop.
Save blork/8c45a2b99571719c0f55b39d2ac35434 to your computer and use it in GitHub Desktop.
Simple Debouncer in Swift 4
//
// Debouncer.swift
//
// Created by Sam Oakley on 20/03/2019.
//
import Foundation
class Debouncer {
private static var pendingRequestWorkItems: [AnyHashable: DispatchWorkItem] = [:]
static func perform(context: AnyHashable, after: DispatchTimeInterval, block: @escaping () -> Void) {
let pendingRequestWorkItem = pendingRequestWorkItems[context]
pendingRequestWorkItem?.cancel()
let requestWorkItem = DispatchWorkItem(block: block)
pendingRequestWorkItems[context] = requestWorkItem
DispatchQueue.main.asyncAfter(deadline: .now() + after,
execute: requestWorkItem)
}
}
@blork
Copy link
Author

blork commented Mar 20, 2019

"Debouncing" is the process by, if there are multiple, rapid calls to a function, only the final one will actually be executed. The perfect example is a web search that happens as the user types - you want to avoid making a call for every character that is entered, but still fire the request without having to hit a "search" button. This way, once the after duration expires with no more calls, the block is run. The context defines the type of the action.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment