set a cooldown on a function (check if it has been 3 seconds since last execution every time function is called) in swift

You can use Timer to execute a function after a certain time interval. Here is an example of how to set a 3-second cooldown on a function in Swift:

main.swift
class CooldownManager {
    var timer: Timer?
    
    func startCoolDown() {
        timer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(endCoolDown), userInfo: nil, repeats: false)
    }
    
    @objc func endCoolDown() {
        timer?.invalidate()
        timer = nil
    }
    
    func isCoolDown() -> Bool {
        return timer != nil
    }
}

func myFunction() {
    static var cooldownManager = CooldownManager()

    if cooldownManager.isCoolDown() {
        print("Function is on cooldown")
        return
    }

    print("Function is executing")
    cooldownManager.startCoolDown()
}
629 chars
29 lines

In this example, CooldownManager class manages the cooldown state and myFunction has a cooldown of 3 seconds. When myFunction is called, it checks if it's on cooldown. If it is, the function exits early. Otherwise, it prints a message and starts a 3-second cooldown by calling startCoolDown method. When the cooldown ends after 3 seconds, endCoolDown method is called and the cooldown is reset.

Note: This code assumes you want to prevent the function from executing again until the cooldown has expired. If not, adjust the code accordingly.

related categories

gistlibby LogSnag