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
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
timer.invalidate()
self?.debouncingTimer = nil
}
// your heavy functionality
}
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)