Skip to content

Instantly share code, notes, and snippets.

@xakpc
Created June 5, 2022 18:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save xakpc/a5621a3147a6b8fc48e66b1611538973 to your computer and use it in GitHub Desktop.
Save xakpc/a5621a3147a6b8fc48e66b1611538973 to your computer and use it in GitHub Desktop.
a simple countdown timer with dotnet Blazor
<div class = "clock">
<h1>@Time</h1>
</div>
using System.Timers;
using Microsoft.AspNetCore.Components;
public partial class Countdown : ComponentBase, IDisposable
{
private System.Timers.Timer _timer = null!;
private int _secondsToRun = 0;
protected string Time { get; set; } = "00:00";
[Parameter]
public EventCallback TimerOut { get; set; }
public void Start(int secondsToRun)
{
_secondsToRun = secondsToRun;
if (_secondsToRun > 0)
{
Time = TimeSpan.FromSeconds(_secondsToRun).ToString(@"mm\:ss");
StateHasChanged();
_timer.Start();
}
}
public void Stop()
{
_timer.Stop();
}
protected override void OnInitialized()
{
_timer = new System.Timers.Timer(1000);
_timer.Elapsed += OnTimedEvent;
_timer.AutoReset = true;
}
private async void OnTimedEvent(object? sender, ElapsedEventArgs e)
{
_secondsToRun--;
await InvokeAsync(() =>
{
Time = TimeSpan.FromSeconds(_secondsToRun).ToString(@"mm\:ss");
StateHasChanged();
});
if (_secondsToRun <= 0)
{
_timer.Stop();
await TimerOut.InvokeAsync();
}
}
public void Dispose()
{
_timer.Dispose();
}
}
.clock {
color: var(--color-tone-1);
font-family: sans-serif;
display: flex;
justify-content: center;
align-items: center;
flex-grow: 1;
overflow: hidden;
}
@N1koV373z
Copy link

I have a question! What does the public EventCallback TimerOut { get; set; } here?

@xakpc
Copy link
Author

xakpc commented Mar 3, 2023

I have a question! What does the public EventCallback TimerOut { get; set; } here?

it allows you to do some actions on the timer completion
when used like this

<Countdown @ref="timer" TimerOut="TimerOutCallback"/>
...
    protected override void OnAfterRender(bool firstRender)
    {
        if (firstRender)
        {
            timer.Start(10);
        }
    }

    protected Shared.Countdown timer;

    private void TimerOutCallback()
    {
        ...
    }

@gcnabeel
Copy link

This is really neat! Thanks for sharing it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment