Skip to content

Instantly share code, notes, and snippets.

@developer-shubham101
Last active May 20, 2022 11:26
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 developer-shubham101/f9b0063cac2e09804ed3be43d81ef7ca to your computer and use it in GitHub Desktop.
Save developer-shubham101/f9b0063cac2e09804ed3be43d81ef7ca to your computer and use it in GitHub Desktop.
Debounce example in swift
//
// DebounceViewController.swift
// UpgradeMySelf-ios
//
// Created by Shubham Sharma on 06/05/22.
// Copyright © 2022 Shubham Sharma. All rights reserved.
//
import UIKit
class DebounceViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
tabBarItem.tag = TabbarItemTag.secondViewConroller.rawValue
view.backgroundColor = .red
let debouncedFunction = debounce(interval: 200, queue: DispatchQueue.main, action: { (identifier: String) in
print("called: \(identifier)")
})
debouncedFunction("1")
DispatchQueue.global(qos: .background).async {
debouncedFunction("1")
usleep(100 * 1000)
debouncedFunction("2")
usleep(100 * 1000)
debouncedFunction("3")
usleep(100 * 1000)
debouncedFunction("4")
usleep(300 * 1000) // waiting a bit longer than the interval
debouncedFunction("5")
usleep(100 * 1000)
debouncedFunction("6")
usleep(100 * 1000)
debouncedFunction("7")
usleep(300 * 1000) // waiting a bit longer than the interval
debouncedFunction("8")
usleep(100 * 1000)
debouncedFunction("9")
usleep(100 * 1000)
debouncedFunction("10")
usleep(100 * 1000)
debouncedFunction("11")
usleep(100 * 1000)
debouncedFunction("12")
}
}
typealias Debounce<T> = (_ : T) -> Void
func debounce<T>(interval: Int, queue: DispatchQueue, action: @escaping Debounce<T>) -> Debounce<T> {
var lastFireTime = DispatchTime.now()
let dispatchDelay = DispatchTimeInterval.milliseconds(interval)
return { param in
lastFireTime = DispatchTime.now()
let dispatchTime: DispatchTime = DispatchTime.now() + dispatchDelay
queue.asyncAfter(deadline: dispatchTime) {
let when: DispatchTime = lastFireTime + dispatchDelay
let now = DispatchTime.now()
if now.rawValue >= when.rawValue {
action(param)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment