7
votes

I created a .razor Notification Component in Blazor, and I'm trying to autoclose the notification div after xx seconds.

So far it works with this Method

 private async Task CloseToast(Guid Id, bool autoclose = false)
{
    if (autoclose)
    {
        await Task.Delay(TimeSpan.FromSeconds(5));
    }

   //Code to remove the notification from list
    StateHasChanged();
}

The problem is that for 5 seconds the UI data binding is stuck, any one way or two way binding update to variables (text fields etc..) is on hold until the Notification is closed and the Task resumes.

How can I launch a method or code block after xx seconds without blocking the main UI task in Blazor?

2

2 Answers

16
votes

A component with a timer that counts back


<h3>@Time</h3>

@code {
    [Parameter] public int Time { get; set; } = 5;

    public async void StartTimerAsync()
    {
        while (Time > 0)
        {
            Time--;
            StateHasChanged();
            await Task.Delay(1000);
        }
    }

    protected override void OnInitialized()
        => StartTimerAsync();
}

Usage:

<Component />
<Component Time="7"/>

Tested on client side Blazor. Should behave the same way in server-side Blazor. Hope this helps

0
votes

You can use .NET Timer from System.Timers as well and set the Delay in milisec. When it elapsed event will triggered and you can put your logic into the event handler. If you don't want to bother with all the config and Disposing of Timer you can use this Nuget package. It is a very convenient wrapper for the Timer with many extra features see docs.

<AdvancedTimer Occurring="Times.Once()" IntervalInMilisec="@_closeInMs" AutoStart="true" OnIntervalElapsed="@(e => { IsVisible = false; })" />
@code {
  private int _closeInMs = 5000;
  ...
}