Delay an action: Debounce and throttle

Delay an action: Debounce and throttle

It can be sometimes interesting to delay an action, for many reasons, but performance is the principal one. Let take an example: you have a searchbox and you need to make a request each time the content changes, if the user types very quickly, it will be totally useless to make a request at every KeyUp events.

Solution: Debouncing

What is deboucing?

The origin is electronic. Mechanical switches don’t make or break a connection cleanly due to microscopic conditions on the contact surface. This is referred to as “Switch Bounce” and can cause problems in digital circuits.

switch_debounce_04_lrg

In our case, we will do exactly the same thing but with actions: we will wait until the user stops typing during an interval.

Here is a simple class to do it:

using System;
using Windows.UI.Xaml;

namespace Huyn.Utils
{
public class Delayer
{
private DispatcherTimer _timer;
public Delayer(TimeSpan timeSpan)
{
  _timer = new DispatcherTimer() { Interval = timeSpan };
  _timer.Tick += Timer_Tick;
}

public event RoutedEventHandler Action;

private void Timer_Tick(object sender, object e)
{
  _timer.Stop();
  if (Action != null)
    Action(this, new RoutedEventArgs());
}

public void ResetAndTick()
{
  _timer.Stop();
  _timer.Start();
}

public void Stop()
{
  _timer.Stop();
}
}
}

And usage:

_searchWithDelay = new Delayer(TimeSpan.FromSeconds(2));
_searchWithDelay.Action += (sender, e) =>
{
  Search();
};

private void Page_KeyUp(CoreWindow coreWindow, KeyEventArgs e)
{
  searchWithDelay.ResetAndTick();
}

 

What about Throttle?

Throttle versus Debounce

Contrary to Debounce, Throttle will not wait the end of an action, but it will limit the number of call of this action. One example: with a delay of 4 seconds, if an user types a key every second, Throttle will call the action every 2 seconds whereas Debounce will wait that the user stops to type during 4 seconds.

How to implement it?

It’s very easy to implement, we only need to add the method:


public void ResetAndTick()
{
  _timer.Start();
}

and use it:

private void Page_KeyUp(CoreWindow coreWindow, KeyEventArgs e)
{
  searchWithDelay.ResetAndTick();
}

Conclusion

This code is very simple, but don’t hesitate to use it to improve performance of your app!

 

Comments are closed.