Skip to content

Instantly share code, notes, and snippets.

@thomsmed
Last active November 7, 2021 15:02
Show Gist options
  • Save thomsmed/4f3ffdbdf3123c8cf4221babd6b6ba7f to your computer and use it in GitHub Desktop.
Save thomsmed/4f3ffdbdf3123c8cf4221babd6b6ba7f to your computer and use it in GitHub Desktop.
Basic debounce function in Swift
//
// debounce.swift
//
import Fundation
func debounce(delay: TimeInterval, queue: DispatchQueue = .main, action: @escaping (() -> Void)) -> () -> Void {
var currentWorkItem: DispatchWorkItem?
var lastFire: TimeInterval = 0
return {
let now = Date().timeIntervalSinceReferenceDate
let remainingDelay = lastFire + delay - now
let workItem = DispatchWorkItem(block: action)
if remainingDelay > 0 {
currentWorkItem?.cancel()
queue.asyncAfter(deadline: .now() + remainingDelay, execute: workItem)
} else {
queue.asyncAfter(deadline: .now() + delay, execute: workItem)
lastFire = now
}
currentWorkItem = workItem
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment