Timer to count down in VB.Net 2010? - vb.net

I'm trying to use a timer to count down from a specified time I choose with the time being separated into minutes and seconds using the format MM:SS and then stop when the time reaches 00:00.
So far I've used a previous answer that was found on here and modified it to the best of my knowledge with counting down although I've hit a snag in which when the timer successfully starts counting down, it's delayed and out of sync when counting down the minutes.
For example, counting down from 120 seconds;
02:00 >
02:59 >
02:58 >
02:57 >
02:56 >
02:55
And then when continuing to count down past 90 seconds under the same test;
02:30 >
01:29 >
01:28 >
01:27 >
01:26 >
01:25
When the countdown reaches 00 or 30 seconds, it incorrectly displays the minutes left and can't understand or figure out how to fix it.
Here is my code for my Counting Timer;
Private Sub tmrCountdown_Tick(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles tmrCountdown.Tick
SetTime = SetTime - 1
lblTime.Text = FormatTime(SetTime)
If SetTime = 0 Then
tmrCountdown.Enabled = False
End If
End Sub
Here is my code for the Function formatting the time;
Public Function FormatTime(ByVal Time As Integer) As String
Dim Min As Integer
Dim Sec As Integer
'Minutes
Min = ((Time - Sec) / 60) Mod 60
'Seconds
Sec = Time Mod 60
Return Format(Min, "00") & ":" & Format(Sec, "00")
End Function
And here is my code for the Form Load;
Private Sub frmSinglePlayer_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
'Setting the time.
SetTime = 120
lblTime.Text = FormatTime(SetTime)
tmrCountdown.Enabled = True
End Sub
I've set;
Dim SetTime As Integer
At the top of my Public Class so I am able to input a specified time into the countdown timer. This is probably something incredibly silly and I can't figure out what it is.
Any help is greatly appreciated and please bare in mind, I am a beginner at programming and get easily confused with large walls of code. (I can barely understand the Function as it is.)
Thank you for helping!

Play with this:
Public Class frmSinglePlayer
Private TargetDT As DateTime
Private CountDownFrom As TimeSpan = TimeSpan.FromMinutes(3)
Private Sub frmSinglePlayer_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
tmrCountdown.Interval = 500
TargetDT = DateTime.Now.Add(CountDownFrom)
tmrCountdown.Start()
End Sub
Private Sub tmrCountdown_Tick(sender As Object, e As System.EventArgs) Handles tmrCountdown.Tick
Dim ts As TimeSpan = TargetDT.Subtract(DateTime.Now)
If ts.TotalMilliseconds > 0 Then
lblTime.Text = ts.ToString("mm\:ss")
Else
lblTime.Text = "00:00"
tmrCountdown.Stop()
MessageBox.Show("Done")
End If
End Sub
End Class

Take a tested sample of countdown timer. Make the changes you need(ex the format of the time).
Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
SetTime = 70
AddHandler dtTimer.Tick, AddressOf dtTimer_Tick
dtTimer.Interval = New TimeSpan(0, 0, 1)
dtTimer.Start()
End Sub
Private Property SetTime As Integer
Private Sub dtTimer_Tick(sender As Object, e As EventArgs)
Dim iMinutes As Integer
Dim iSeconds As Integer
If SetTime = 0 Then
dtTimer.Stop()
txtTime.Text = "0:0"
Exit Sub
End If
SetTime -= 1
iMinutes = Math.Floor(SetTime / 60)
iSeconds = SetTime Mod 60
txtTime.Text = iMinutes & ":" & iSeconds
End Sub

Try this
'the amount of time to countdown from
Dim countDownFrom As New TimeSpan(0, 0, 10) 'ten seconds
'a Stopwatch to track how long running
Dim stpw As New Stopwatch
Private Sub Button1_Click(sender As Object, _
e As EventArgs) Handles Button1.Click
Timer1.Interval = 250 'how often to update display
Timer1.Start() 'start the display updater
stpw.Reset() 'restart the stopwatch
stpw.Start()
'or depending on version of .Net
'stpw.Restart
End Sub
Private Sub Timer1_Tick(sender As Object, _
e As EventArgs) Handles Timer1.Tick
If stpw.Elapsed <= countDownFrom Then
Dim toGo As TimeSpan = countDownFrom - stpw.Elapsed
lblTime.Text = String.Format("{0:00}:{1:00}:{2:00}", toGo.Hours, toGo.Minutes, toGo.Seconds)
Else
Timer1.Stop()
stpw.Stop()
End If
End Sub

your mistake in your original code is that you are using the MOD operater incorrectly.
'Minutes
Min = ((Time - Sec) / 60) Mod 60
'Seconds
Sec = Time Mod 60
At 2:00 you see 2:00 because:
Min = ((120-00) / 60 ) MOD 60 = 2 MOD 60 = 2
Sec = 120 MOD 60 = 0
At 1:59 you see 2:59 because
Min = (119 / 60) MOD 60 = 1.98 MOD 60 = 1.98 = 2
Sec = 119 MOD 60 = 59
After 31 seconds your minutes changes from 2 to 1 because
Min = (89 / 60) MOD 60 = 1.48 MOD 60 = 1.48 = 1

More simply:
Format((Math.Floor(lSeconds / 60)), "00") & ":" & Format((lSeconds Mod 60), "00")

Public SetTime As Integer = 0
Public Min As Integer = 0
Public Sec As Integer = 0
Public Decimaal As Decimal = 0
Public Function FormatTime(ByVal Time As Integer) As String
'Minutes
Min = Fix(SetTime / 60000)
'Decimaal
Decimaal = (SetTime / 60000) - Min
'Seconden
Sec = Fix(Decimaal * 60)
Return Format(Min, "00") & ":" & Format(Sec, "00")
End Function
Private Sub tmrCountdown_Tick(sender As Object, e As EventArgs) Handles tmrCountdown.Tick
SetTime = SetTime - 1000
lblCountdown.Text = FormatTime(SetTime)
tmrCountdown.Enabled = True
If SetTime = 0 Then
tmrCountdown.Enabled = False
End If
End Sub

You could just do
For i = 120 to 0 step -1
Console.writeline(i)
Next
But be aware it will instantly put them on the screen and it won't do it 1 at a time

Related

How to make a countdown timer that a custom control

I am trying to create a count down timer control that I will be adding to a bigger project later. The control I am trying to make is a countdown timer that is given an initial value of 60 secs but also allows the user to change that value if needed. I am doing this in Visual Studio using Visual Basics.
Public Class UserControl1
Dim timeTick As Integer
Dim min As Integer
Dim setSecs As Integer = 60
Dim sec As Integer = 120
Private Sub UserControl1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Timer.Start()
End Sub
Private Sub Timer_Tick(sender As Object, e As EventArgs) Handles Timer.Tick
sec -= 1
min = sec % 60
Label1.Text = min & " : " & sec
If sec < 60 Then
min = 1 + timeTick
Label1.Text = min & " : " & sec
End If
End Sub
Property HowLong As Integer
Get
Return setSecs
End Get
Set(value As Integer)
setSecs = value
End Set
End Property
End Class
Set your Timer Interval to something less than one second; I used 250.
Then store the time in the future that is XXX seconds away, representing your countdown duration.
At each tick, simply subtract the current time from the stored future time to get a TimeSpan. Update your label with the TimeSpan value using ToString().
When the HowLong property is changed, update the target time and restart your timer...easy peesy.
All together, it'd look something like this:
Public Class UserControl1
Private target As DateTime
Private setSecs As Integer = 60
Private Sub UserControl1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
target = DateTime.Now.AddSeconds(HowLong)
Timer.Start()
End Sub
Private Sub Timer_Tick(sender As Object, e As EventArgs) Handles Timer.Tick
Dim ts As TimeSpan = target.Subtract(DateTime.Now)
If ts.TotalMilliseconds > 0 Then
Label1.Text = "-" & ts.ToString("mm\:ss")
Else
Label1.Text = "00:00"
Timer.Stop()
End If
End Sub
Property HowLong As Integer
Get
Return setSecs
End Get
Set(value As Integer)
setSecs = value
Timer.Stop()
target = DateTime.Now.AddSeconds(HowLong)
Timer.Start()
End Set
End Property
End Class
The authors response:
Technically your way will work to I will post my solution below I did
it slightly differently. – Thomas
From my comments on the authors own submission:
The problem with this type of approach is that the Timer control is
not accurate. It is only guaranteed to not fire before the interval
has transpired. In fact it will almost always fire after the interval
with some extra "slop". For short periods (seconds/minutes), you won't
notice. For longer periods (hours), you will, as the accumulated slop
becomes bigger as time passes. Whether this matters is completely
dependent upon your application. – Idle_Mind
Technically speaking, here's a quick example of how inaccurate simply incrementing/decrementing a counter using a 1 second Timer can be:
' Timer1.Interval was set to 1000 (timer fires every "second")
Private seconds As Integer = 0
Private start As DateTime = DateTime.Now
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
seconds = seconds + 1
Label1.Text = seconds
Label2.Text = DateTime.Now.Subtract(start).TotalSeconds
End Sub
After only 1 hour and 15 minutes, the counter method on the left is already off by 4 seconds from the actual time that has passed:
A key advantage of the DateTime/TimeSpan method is that the time calculation is independent from the Timer. That is to say that the frequency at which the Timer fires has no bearing on how accurate the time calculation is.
This code below is how I made a simple timer control that countdown from a set value. Also, it has 2 buttons that pause and resume the time. This control will not work if in design mode and the timer interval is set to 1000. If you have any questions about how it works just leave a comment.
Public Class UserControl1
Dim timeRemaing As Integer = 60
Private Sub UserControl1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Timer.Start()
End Sub
Private Sub Timer_Tick(sender As Object, e As EventArgs) Handles Timer.Tick
Dim sec As Integer
Dim mins As Integer
Dim timerFormat As String
If Not Me.DesignMode Then
sec = timeRemaing Mod 60
mins = timeRemaing \ 60
If sec < 10 Then
timerFormat = mins.ToString + ":0" + sec.ToString
Else
timerFormat = mins.ToString + ":" + sec.ToString
End If
If timeRemaing > 0 Then
timeRemaing -= 1
lblTime.Text = timerFormat
Else
Timer.Stop()
lblTime.Text = "The Time has Stop!!!"
End If
End If
End Sub
Public Property HowLong As Integer
Get
Return timeRemaing
End Get
Set(value As Integer)
If value <= 0 Then
Timer.Stop()
ElseIf value > 0 Then
Timer.Start()
timeRemaing = value
End If
End Set
End Property
Private Sub btnPause_Click(sender As Object, e As EventArgs) Handles btnPause.Click
Timer.Stop()
End Sub
Private Sub btnResume_Click(sender As Object, e As EventArgs) Handles btnResume.Click
Timer.Start()
End Sub
End Class

Convert minutes to hours: ,minutes in vb.net

I want to convert total minutes to hours and minutes hh:mm..
This is my code
Private Sub TextBox5_TextChanged(sender As Object, e As EventArgs) Handles TextBox5.TextChanged
Dim TotalMinute As Int32
Dim Minute As Int32
Dim Hour As Int32
Try
TotalMinute = CType(TextBox9.Text, Int32)
TotalMinute = TotalMinute Mod 1440
Hour = TotalMinute \ 60
Minute = TotalMinute Mod 60
TextBox5.Text = FormatTwoDigits(Hour) & ":" & FormatTwoDigits(Minute)
Catch ex As Exception
Exit Sub
End Try
End Sub
Private Function FormatTwoDigits(ByVal i As Int32) As String
If 30 > i Then
FormatTwoDigits = "0" & i.ToString
Else
FormatTwoDigits = i.ToString
End If
End Function
This code works fine under 24 hours.. but counts back from 0 after 24...
For example if the input is 1500 minutes it should say 25:00 not 01:00
Or you could let .Net do the work
Dim ts As TimeSpan = TimeSpan.FromMinutes(TotalMinute)
Dim s As String = String.Format("{0:00}:{1:00}", Math.Floor(ts.TotalHours), ts.Minutes)
Remove your TotalMinute = TotalMinute Mod 1440 line, which is saying to get rid of any "day" portion if the total minutes exceeds one day. (60 minutes = 1 hour, 24 hours = 1 day, therefore 1440 minutes = 1 day.)
I'd do something more like:
Private Sub TextBox5_TextChanged(sender As Object, e As EventArgs) Handles TextBox5.TextChanged
Dim TotalMinute As Integer
If Integer.TryParse(TextBox9.Text, TotalMinute) Then
Dim ts As TimeSpan = TimeSpan.FromMinutes(TotalMinute)
TextBox5.Text = CType(ts.TotalHours, Integer).ToString("00") & ":" & ts.Minutes.ToString("00")
End If
End Sub

Winforms timer not accurate

I have an app that uses a System.Windows.Forms.Timer and am seeing issues with the timer interval. When I use an interval of 1000 for a duration of 180 seconds the elapsed time is consistently around 183 seconds. When I use an interval of 995, the elapsed time is accurate (i.e. 180 seconds). I have tried this on 3 different PCs with the same results on each. The code below uses 2 textboxes to display the start and end times and a label as a countdown timer.
Can anyone explain this behavior?
Public Class Form1
Private WithEvents tmr As New System.Windows.Forms.Timer
Private Duration As Integer = 180
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
RunTimer()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lblActivityTimer.Text = FormatCounter(Duration)
tmr.Interval = 1000
End Sub
Private Sub RunTimer()
tmr.Start()
TextBox1.Text = Now.ToString()
End Sub
Private Function FormatCounter(sec As Integer) As String
Dim Hours, Minutes, Seconds As Integer
Hours = sec \ 3600
Seconds = sec Mod 3600
Minutes = Seconds \ 60
Seconds = sec Mod 60
FormatCounter = Hours.ToString.PadLeft(2, "0"c) & ":" _
& Minutes.ToString.PadLeft(2, "0"c) _
& ":" _
& Seconds.ToString.PadLeft(2, "0"c)
End Function
Private Sub tmr_Tick(sender As Object, e As EventArgs) Handles tmr.Tick
Duration -= 1
lblActivityTimer.Text = FormatCounter(Duration)
If Duration = 0 Then
TextBox2.Text = Now.ToString()
tmr.Stop()
End If
End Sub
End Class
Use a Stop Watch, it provides a set of methods and properties that you can use to accurately measure elapsed time.
Shared Sub Main(ByVal args() As String)
Dim stopWatch As New Stopwatch()
stopWatch.Start()
Thread.Sleep(10000)
stopWatch.Stop()
' Get the elapsed time as a TimeSpan value.
Dim ts As TimeSpan = stopWatch.Elapsed
' Format and display the TimeSpan value.
Dim elapsedTime As String = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10)
Console.WriteLine( "RunTime " + elapsedTime)
End Sub 'Main
There are two readily available Timer object alternatives:
System.Threading.Timer (explained here, my first pick)
System.Timers.Timer (explained here)

Progressbar decrement using datetime

I am trying to decrement timer from 30 minutes to 0 mins and update the progressbar with the decrement of time
I have a progressbar control on my form and set it's min val to '0' and max value to '60' and incremental step to '1'
I have stucked with it right now..
This is what I have done so far:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ProgressBar1.Value = 60
End sub
Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick
Dim dFrom As DateTime
Dim dTo As DateTime
Dim sDateFrom As String = DateTime.Now
Dim sDateTo As String = lblLogOutTime.Text
If RemainingTime.Text = "00:00:00" Then
RemainingTime.Text = "Time's up!"
ProgressBar1.Value = 0
Timer2.Stop()
ElseIf DateTime.TryParse(sDateFrom, dFrom) AndAlso DateTime.TryParse(sDateTo, dTo) Then
Timer2.Start()
ProgressBar1.Value -= 1
ProgressBar1.Update()
Dim TS As TimeSpan = dTo - dFrom
Dim hour As Integer = TS.Hours
Dim mins As Integer = TS.Minutes
Dim secs As Integer = TS.Seconds
Dim timeDiff As String = ((hour.ToString("00") & ":") + mins.ToString("00") & ":") + secs.ToString("00")
RemainingTime.Text = timeDiff
End If
It seems like you have a lot of extra code in there. For instance DateTime types converted to string, then back to Date.
Private LogOutTime as Date ' destination time
Form Load/Restart sub:
LogOutTime = DateTime.Now.AddMinutes(30)
' 1 min tick
Timer2.Interval = 60 * 1000 ' 1 min timer
ProgressBar1.Value = 30 ' 30 min countdown
ProgressBar1.Maximum = 31
Timer2.Start
Private Sub Timer2_Tick(...
Dim Ts as TimeSpan = LogOutTime - DateTime.Now
If Ts.Minutes = 0 Then ' or TS,Ticks
RemainingTime.Text = "Time's up!"
ProgressBar1.Value = 0
Timer2.Stop()
Exit Sub
End If
' better to convert Ts.Ticks to a 0-30 value
' so the timer interval can be different than 1 min
ProgressBar1.Value -= 1
RemainingTime.Text = New DateTime(Ts.Ticks).ToString("hh:mm:ss")
Timer2.Start()
End Sub
There are several ways to format the time remaining depending on your .NET version. I dont know what Timer1 does, it might interfere. If the Timer interval was 20 or 30 secs you could show seconds ticking away but you'd have to calculate the progressbar value from Timespan.Ticks rather than simply decrement.

Show Remaining time TimeSpan

I'm getting problems trying to show the remainig time of a operation
The problem is only with the remaining timer, I get a negative values...
This is a example of a operation of 10000 ms (10 secs):
So anyway if i remove the "-" char from the timespan the hour and the minute stills incorrects values...
Dim time_out as integer = 60000 ' 'Milisegundos
Dim StartTime As DateTime ' Tiempo inicio
Dim EndTime As DateTime ' Tiempo final
Dim ElapsedTime As TimeSpan ' Tiempo transcurrido
Dim RemainingTime As TimeSpan ' Tiempo restante
' Elapsed Time
#Region " Elapsed Time Function "
Public Function Print_Elapsed_Time()
If StartTime.ToString = "01/01/0001 0:00:00" Then
StartTime = Now
StartTime = StartTime.AddSeconds(-1)
End If
ElapsedTime = Now().Subtract(StartTime)
Return String.Format("{0:00}:{1:00}:{2:00}", CInt(Math.Floor(ElapsedTime.TotalHours)) Mod 60, CInt(Math.Floor(ElapsedTime.TotalMinutes)) Mod 60, CInt(Math.Floor(ElapsedTime.TotalSeconds)) Mod 60)
End Function
#End Region
#Region " Remaining Time Function "
Public Function Print_Remaining_Time()
If EndTime.ToString = "01/01/0001 0:00:00" Then
EndTime = Now
EndTime = EndTime.AddMilliseconds(Time_Out - 1000)
End If
RemainingTime = Now().Subtract(EndTime)
Return String.Format("{0:00}:{1:00}:{2:00}", CInt(Math.Floor(RemainingTime.TotalHours)) Mod 60, CInt(Math.Floor(RemainingTime.TotalMinutes)) Mod 60, CInt(Math.Floor(RemainingTime.TotalSeconds)) Mod 60).Replace("-", "")
End Function
#End Region
Here is an example of a countdown from 10 seconds using a timer and two labels
'example - countdown from 10 secs
Dim countdown As New TimeSpan(0, 0, 10)
Dim stpw As New Stopwatch
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If stpw.IsRunning Then
stpw.Stop()
Timer1.Stop()
Else
stpw.Stop()
stpw.Reset()
stpw.Start()
Timer1.Interval = 100
Timer1.Start()
End If
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
'label1 - elapsed time
'label2 - time remaining
If stpw.Elapsed <= countdown Then
Label1.Text = stpw.Elapsed.ToString
Label2.Text = (countdown - stpw.Elapsed).ToString
Else
stpw.Stop()
Label1.Text = countdown.ToString
Label2.Text = "00:00:00"
End If
End Sub
I think for the End Time you want :
RemainingTime = EndTime.Subtract(Now)
Otherwise, I'm not sure how you initialized these, but I made this change :
Dim StartTime As DateTime = DateTime.MinValue ' Tiempo inicio
Dim EndTime As DateTime = DateTime.MinValue ' Tiempo final
and also :
If StartTime = DateTime.MinValue Then ' ... etc '
but perhaps a flag or something is altogether a better way to signal a reset.