Last active
November 7, 2021 15:02
-
-
Save thomsmed/4f3ffdbdf3123c8cf4221babd6b6ba7f to your computer and use it in GitHub Desktop.
Basic debounce function in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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