Created
May 21, 2016 19:15
-
-
Save NiclasOlofsson/9f770405687c045e55d3e675d99dbed0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
public class CountDownTimer | |
{ | |
private Stopwatch _startTimer; | |
private TimeSpan _delay; | |
private long _currentTick; | |
private readonly int _skipTicks; | |
private readonly Action<TimeSpan> _tickAction; | |
private readonly Action _endAction; | |
public CountDownTimer(TimeSpan delay, Action endAction, Action<TimeSpan> tickAction = null, int skipTicks = 20) | |
{ | |
_delay = delay; | |
_tickAction = tickAction; | |
_skipTicks = skipTicks; | |
_endAction = endAction; | |
} | |
public void Start() | |
{ | |
_startTimer = new Stopwatch(); | |
_startTimer.Start(); | |
} | |
public void Tick() | |
{ | |
_currentTick++; | |
Tick(_currentTick); | |
} | |
public void Tick(long tickTime) | |
{ | |
_currentTick = tickTime; | |
if (_startTimer == null || !_startTimer.IsRunning) return; | |
if (_startTimer.IsRunning && tickTime%_skipTicks == 0) | |
{ | |
if (_startTimer.Elapsed > _delay) | |
{ | |
_startTimer.Stop(); | |
_endAction?.Invoke(); | |
} | |
else | |
{ | |
TimeSpan timeLeft = _delay - _startTimer.Elapsed; | |
_tickAction?.Invoke(timeLeft); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment