Created
June 5, 2022 18:30
-
-
Save xakpc/a5621a3147a6b8fc48e66b1611538973 to your computer and use it in GitHub Desktop.
a simple countdown timer with dotnet Blazor
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
<div class = "clock"> | |
<h1>@Time</h1> | |
</div> |
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.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(); | |
} | |
} |
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
.clock { | |
color: var(--color-tone-1); | |
font-family: sans-serif; | |
display: flex; | |
justify-content: center; | |
align-items: center; | |
flex-grow: 1; | |
overflow: hidden; | |
} |
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()
{
...
}
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
I have a question! What does the public EventCallback TimerOut { get; set; } here?