DEV Community

Amerigo Mancino
Amerigo Mancino

Posted on

How to create a debouncing timer in Swift

One common problem people tends to underestimate is when users decide to stress a heavy functionality within your app, for example by pressing a button numerous times in a small span, resulting in crashes and undefined behaviors.

One way to overcome this problem is to create a debouncing timer. We do that by defining a couple of variables inside the class where the functionality is used:

private var debouncingTimer: Timer? = nil
private let DEBOUNCE_TIME: TimeInterval = 0.5
Enter fullscreen mode Exit fullscreen mode

The debounce time is the minimum interval for the heavy code to occur. Within that time span other user interactions will be ignored.

Then, from within the outlet of the button who triggers your heavy functionality we perform the following:

if debouncingTimer == nil || debouncingTimer?.isValid == false {
    self.debouncingTimer = Timer.scheduledTimer(
        withTimeInterval: DEBOUNCE_TIME,
        repeats: false) { [weak self] timer in
                self?.debouncingTimer = nil

    // your heavy functionality
Enter fullscreen mode Exit fullscreen mode

By doing this, we set a timer every time the heavy code is triggered and we protect it until the timer keeps running.

When the timer is invalidated, the functionality becomes available for the user again.

Top comments (0)