Created
November 7, 2021 14:51
-
-
Save thomsmed/6ee78e865314f99bdfb165fe9817d4c1 to your computer and use it in GitHub Desktop.
Basic throttle 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
// | |
// trottle.swift | |
// | |
import Foundation | |
func throttle(interval: TimeInterval, queue: DispatchQueue = .main, action: @escaping (() -> Void)) -> () -> Void { | |
var lastFire: TimeInterval = 0 | |
return { | |
let now = Date().timeIntervalSinceReferenceDate | |
let delay = lastFire + interval - now | |
let workItem = DispatchWorkItem(block: action) | |
if delay > 0 { | |
queue.asyncAfter(deadline: .now() + delay, execute: workItem) | |
lastFire = now + delay | |
} else { | |
queue.async(execute: workItem) | |
lastFire = now | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment