Skip to content

Instantly share code, notes, and snippets.

@blork
Last active March 20, 2019 14:36
Show Gist options
  • 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)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment