Skip to content

Instantly share code, notes, and snippets.

@audinue
Last active May 14, 2017 06:55
Show Gist options
  • Save audinue/4292e558db444bca83ddc9fb6e4f5810 to your computer and use it in GitHub Desktop.
Save audinue/4292e558db444bca83ddc9fb6e4f5810 to your computer and use it in GitHub Desktop.
C# Debounce
using System;
using System.Threading;
using System.Threading.Tasks;
/**
* <summary>C# implementation of JavaScript's setTimeout.</summary>
*/
public static CancellationTokenSource setTimeout(Action callback, int delay = 100)
{
CancellationTokenSource source = new CancellationTokenSource();
Task.Delay(delay, source.Token)
.ContinueWith(task =>
{
if (!task.IsCanceled)
{
callback();
}
});
return source;
}
/**
* <summary>C# implementation of JavaScript's clearTimeout.</summary>
*/
public static void ClearTimeout(CancellationTokenSource source)
{
source.Cancel();
}
/**
* <summary>Debounces the callback.</summary>
*/
public static Action Debounce(Action callback, int delay = 100)
{
CancellationTokenSource source = null;
return () =>
{
if (source != null)
{
ClearTimeout(source);
}
source = setTimeout(() =>
{
source = null;
callback();
}, delay);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment