Skip to content

Instantly share code, notes, and snippets.

@pablopioli
Created July 20, 2020 20:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pablopioli/f7da61e490c575a306501067bfd0fca1 to your computer and use it in GitHub Desktop.
Save pablopioli/f7da61e490c575a306501067bfd0fca1 to your computer and use it in GitHub Desktop.
using System;
using System.Timers;
namespace Blazored.Toast
{
internal class CountdownTimer : IDisposable
{
private Timer _timer;
private int _percentComplete;
internal Action<int> OnTick;
internal Action OnElapsed;
internal CountdownTimer(int timeout)
{
_timer = new Timer(timeout * 1000)
{
Interval = timeout * 1000 / 100,
AutoReset = true
};
_timer.Elapsed += HandleTick;
_percentComplete = 0;
}
internal void Start()
{
_timer.Start();
}
private void HandleTick(object sender, ElapsedEventArgs args)
{
_percentComplete += 1;
OnTick?.Invoke(_percentComplete);
if (_percentComplete >= 100)
{
OnElapsed?.Invoke();
}
}
public void Dispose()
{
_timer.Dispose();
_timer = null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment