Search
 
SCRIPT & CODE EXAMPLE
 

SWIFT

debounce in swift

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)
            }
        }
    }
}

//How to use 

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")
}


Comment

PREVIOUS NEXT
Code Example
Swift :: Function Inside Swift Struct 
Swift :: Swift Closure Parameters 
Swift :: swiftui text editor 
Swift :: swift int max 
Swift :: swift guard statement 
Swift :: swift function declaration 
Swift :: fetch request core data 
Swift :: swift array map example 
Swift :: swift firebase realtime db class 
Swift :: swift out of bound elelemnt 
Swift :: Swift Static Properties 
Swift :: after redirect from another viewcontroller in swift 5 make full view view controller 
Swift :: Swift Change Value of Dictionary 
Swift :: table flutter stackoverflow 
Swift :: procedural audio with swift 
Swift :: swift array chunks 
Swift :: access tuple elements 
Swift :: how to switch tabs in xcode 
Swift :: SwifUI call the function in the cordinator 
Swift :: Swift Comparison Operators 
Swift :: selector cannot call in notification observer swift 
Swift :: swift 5 cancel or end block operation 
Swift :: remove child from scene swift 
Swift :: sizetofit not working swift 
Ruby :: how to check if data is an array or not ruby 
Ruby :: create table if not exist rails 
Ruby :: rails migration polymorphic references 
Ruby :: ruby multiline comment 
Ruby :: ruby string to int 
Ruby :: liquid add date 
ADD CONTENT
Topic
Content
Source link
Name
1+5 =