Last active
May 14, 2017 06:55
-
-
Save audinue/4292e558db444bca83ddc9fb6e4f5810 to your computer and use it in GitHub Desktop.
C# Debounce
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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