Files
GitHawk/Classes/Systems/Debouncer.swift
Hesham Salman 2ec7ba2753 Preventing the search race condition instead of responding to it (#691)
* More explicit approach to search triggers

Cutt reliance off of the singleton store

* Cleaned up optional code-smell

Comments
2017-10-23 17:08:55 -04:00

45 lines
916 B
Swift

//
// Debouncer.swift
// Freetime
//
// Created by Hesham Salman on 10/18/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import Foundation
class Debouncer {
private let delay: Double
private weak var timer: Timer?
var action: (() -> Void)? {
didSet {
debounce()
}
}
init(delay: Double = 0.35) {
self.delay = delay
}
convenience init(delay: Double = 0.35, action: @escaping (() -> Void)) {
self.init(delay: delay)
self.action = action
}
private func debounce() {
timer?.invalidate()
timer = Timer.scheduledTimer(
timeInterval: delay,
target: self,
selector: #selector(Debouncer.executeAction(_:)),
userInfo: nil,
repeats: false
)
}
@objc private func executeAction(_ sender: Timer) {
action?()
}
}