Page 1 of 1

Count down timer

Posted: Sun Jun 25, 2017 2:10 pm
by Bloodz_Ninja
So i've made this code in a project of mines, and i thought id share this piece of it.
Idk if there are any like this already, or better, but this was my method.

First, we declare 2 variables
Code: Select all
Dim seconds, minutes As Integer
Second, in form_load, we assign a value of your choice. My code counts from 7 Minutes, so ill go with 6:59
Code: Select all
seconds = 59
 minutes = 6
Now in a timer, that will be triggered by your choice, add this code
Code: Select all
If seconds >= 10 Then
            Label30.Text = seconds
        Else
            Label30.Text = "0" & seconds
        End If

        Label29.Text = "0" & minutes
        seconds -= 1

        If minutes = 6 And seconds = 0 Then
            minutes -= 1
            seconds = 59
        End If
        If minutes = 5 And seconds = 0 Then
            minutes -= 1
            seconds = 59
        End If
        If minutes = 4 And seconds = 0 Then
            minutes -= 1
            seconds = 59
        End If
        If minutes = 3 And seconds = 0 Then
            minutes -= 1
            seconds = 59
        End If
        If minutes = 2 And seconds = 0 Then
            minutes -= 1
            seconds = 59
        End If
        If minutes = 1 And seconds = 0 Then
            minutes -= 1
            seconds = 59
        End If
        If minutes = 0 And seconds = 59 Then
            Label28.ForeColor = Color.Red
            Label29.ForeColor = Color.Red
            Label30.ForeColor = Color.Red
            Label31.ForeColor = Color.Red
        End If
        If minutes = 0 And seconds = 0 Then
            Timer3.Stop()
            MsgBox("Time's Up!")
            Button1.PerformClick()
        End If
Of course, i did use labels to display the time. They turn red at the 1 minute mark.
Anything you guys dont understand about it, ill be glad to answer your questions

Re: Count down timer

Posted: Mon Jun 26, 2017 10:45 am
by Filip
Why don't you just store number of seconds and then mathematically using Floor and mod determine minutes/seconds?
Personally, I would store only number of seconds or milliseconds.

Re: Count down timer

Posted: Mon Jun 26, 2017 4:12 pm
by Bloodz_Ninja
Good point. But it was more of a spur of the moment kind of thing, also not the best at math either, but once again pretty good point

Re: Count down timer

Posted: Thu Jun 29, 2017 2:20 am
by Filip
When you have a variable with seconds, doing floor(sec / 60) and sec mod 60 would return number of minutes and number of seconds respectively. Not complicated at all, yet saves time by reducing number of if branchings.

Also, this code only works when minutes are less or equal to 6. Otherwise it counts down seconds to infinity. Instead of all those ifs, you could turn it to the following:
Code: Select all
if secs = 0 and mins > 0 then
     mins--
    secs=59
else
// time's up!
end if