Skip to content

Instantly share code, notes, and snippets.

@abhi21git
Last active May 22, 2024 16:01
Show Gist options
  • Save abhi21git/cfc581cd6a19169b40d3cbeaed55a466 to your computer and use it in GitHub Desktop.
Save abhi21git/cfc581cd6a19169b40d3cbeaed55a466 to your computer and use it in GitHub Desktop.
A simple debounce handler for swift
//
// DispatchQueue+Debounce.swift
//
// Created by Abhishek Maurya on 22/05/24.
//
import Foundation
public extension DispatchQueue {
func debounce(after interval: Int, action: @escaping (Any?) -> Void) -> (Any?) -> Void {
var executed: Bool = false
var lastFireTime: DispatchTime = .now()
let dispatchDelay: DispatchTimeInterval = .milliseconds(interval)
return { value in
lastFireTime = .now()
self.asyncAfter(deadline: .now() + dispatchDelay) {
let now: DispatchTime = .now()
let when: DispatchTime = lastFireTime + dispatchDelay
guard now.rawValue >= when.rawValue, !executed else { return }
executed = true
action(value)
}
}
}
}

Usage:

let debouncedWorkItem = DispatchQueue.main.debounce(after: 2000) { value in
    print("Hello World", value ?? "")
}

for i in 0...5 {
    DispatchQueue.global().asyncAfter(deadline: .now() + TimeInterval(i)) {
        debouncedWorkItem(i)
    }
}

Will print Hello World 5

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