How can I add a delay to an event (OnInput) in Blazor ?
For example, if a user is typing in the text field and you want to wait until the user has finished typing.
I have created a set of Blazor components. One of which is Debounced inputs with multiple input types and much more features. Blazor.Components.Debounce.Input is available on NuGet.
You can try it out with the demo app.
Note: currently it is in Preview. Final version is coming with .NET 5. release
There is no single solution to your question. The following code is just one approach. Take a look and adapt it to your requirements. The code resets a timer on each keyup
, only last timer raises the OnUserFinish
event.
@using System.Timers;
...
<input type="text" @bind-value="Data" @bind-value:event="oninput"
@onkeyup="@HandleKeyUp"/>
<p>@Data2</p>
@code {
public string Data { get; set; }
public string Data2 { get; set; }
private System.Timers.Timer aTimer;
protected override void OnInitialized()
{
aTimer = new System.Timers.Timer(1000);
aTimer.Elapsed += OnUserFinish;
aTimer.AutoReset = false;
}
void HandleKeyUp(KeyboardEventArgs e)
{
// remove previous one
aTimer.Stop();
// new timer
aTimer.Start();
}
private void OnUserFinish(Object source, ElapsedEventArgs e)
{
InvokeAsync( () =>
{
Data2 = $"User has finished: {Data}";
StateHasChanged();
});
}
}
One example of use case of this code is avoiding backend requests, because the request is not sent until user stops typing.