Skip to content

Commit

Permalink
TMP
Browse files Browse the repository at this point in the history
  • Loading branch information
tareqimbasher committed Jan 1, 2024
1 parent 078fdbc commit 94e392b
Showing 1 changed file with 34 additions and 2 deletions.
36 changes: 34 additions & 2 deletions src/Core/NetPad.Domain/Utilities/DelegateUtil.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,48 @@ namespace NetPad.Utilities;

public static class DelegateUtil
{
public static Action<T> Debounce<T>(this Action<T> func, int milliseconds = 300)
public static Action Debounce(this Action func, int milliseconds = 300, bool immediate = false)
{
CancellationTokenSource? cancelTokenSource = null;
Task? task = null;

return () =>
{
cancelTokenSource?.Cancel();
cancelTokenSource = new CancellationTokenSource();
if (immediate && (task == null || task.IsCompleted))
{
func();
}
task = Task.Delay(milliseconds, cancelTokenSource.Token)
.ContinueWith(t =>
{
if (t.IsCompletedSuccessfully)
{
func();
}
}, TaskScheduler.Default);
};
}

public static Action<T> Debounce<T>(this Action<T> func, int milliseconds = 300, bool immediate = false)
{
CancellationTokenSource? cancelTokenSource = null;
Task? task = null;

return arg =>
{
cancelTokenSource?.Cancel();
cancelTokenSource = new CancellationTokenSource();
Task.Delay(milliseconds, cancelTokenSource.Token)
if (immediate && (task == null || task.IsCompleted))
{
func(arg);
}
task = Task.Delay(milliseconds, cancelTokenSource.Token)
.ContinueWith(t =>
{
if (t.IsCompletedSuccessfully)
Expand Down

0 comments on commit 94e392b

Please sign in to comment.