Skip to content

Instantly share code, notes, and snippets.

@thomsmed
Created November 7, 2021 14:51
Show Gist options
  • Save thomsmed/6ee78e865314f99bdfb165fe9817d4c1 to your computer and use it in GitHub Desktop.
Save thomsmed/6ee78e865314f99bdfb165fe9817d4c1 to your computer and use it in GitHub Desktop.
Basic throttle function in Swift
//
// 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