Simple Debouncer in Swift

Debouncer term comes from electronic circuits world. As an example, when you press a key on your keyboard, you expect a single contact, but indeed there happens multiple contacts called bouncing. To prevent this and make signal meaningful, there are many debouncer solutions.

In our world, we use debouncer to reduce number of executions for the functions that are called quite often. For example, we can use debouncer for a search-as-you-type UI. Debouncer delays search task for a specified time and if user types a new key before time elapses, debouncer cancels the previous one and delays new task for the specified time again.

Here’s my simple debouncer implementation:

To show it in action:

Only the last task gets executed because of the delay.

Another example:

This time second and fourth tasks are executed. Because:

1- Our delay is 1 second, the last task in 1 second is the second task so it gets executed.

2- Third and fourth task are called after 2 seconds, they beat up our 1 second delay and between the third and fourth, the last one is the fourth task so it gets executed as well.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store