Step 3: Add a countdown timer

  • Article
  • 6 minutes to read

In the third part of this tutorial, you'll add a countdown timer to track the number of seconds that remain for the quiz taker to finish.

To add a countdown timer

  1. Add an integer variable that's named timeLeft, just like you did in the previous procedure. Your code should look like the following.

                    Public Class Form1      ' Create a Random object called randomizer      ' to generate random numbers.     Private randomizer As New Random      ' These integer variables store the numbers      ' for the addition problem.      Private addend1 As Integer     Private addend2 As Integer      ' This integer variable keeps track of the      ' remaining time.     Private timeLeft As Integer                              
                    public partial class Form1 : Form {     // Create a Random object called randomizer      // to generate random numbers.     Random randomizer = new Random();      // These integer variables store the numbers      // for the addition problem.      int addend1;     int addend2;      // This integer variable keeps track of the      // remaining time.     int timeLeft;                              

    Important

    Use the programming language control at the top right of this page to view either the C# code snippet or the Visual Basic code snippet.

    Programming language control for Docs.Microsoft.com

    Now you need a method that actually counts the seconds, such as a timer, which raises an event after the amount of time that you specify.

  2. In the design window, move a Timer control from the Components category of the Toolbox to your form.

    The control appears in the gray area at the bottom of the design window.

  3. On the form, choose the timer1 icon that you just added, and set its Interval property to 1000.

    Because the interval value is milliseconds, a value of 1000 causes the Tick event to fire every second.

  4. On the form, double-click the Timer control, or choose it and then choose the Enter key.

    The code editor appears and displays the method for the Tick event handler that you just added.

  5. Add the following statements to the new event handler method.

                    Private Sub Timer1_Tick() Handles Timer1.Tick      If timeLeft > 0 Then         ' Display the new time left         ' by updating the Time Left label.         timeLeft -= 1         timeLabel.Text = timeLeft & " seconds"     Else         ' If the user ran out of time, stop the timer, show         ' a MessageBox, and fill in the answers.         Timer1.Stop()         timeLabel.Text = "Time's up!"         MessageBox.Show("You didn't finish in time.", "Sorry!")         sum.Value = addend1 + addend2         startButton.Enabled = True     End If  End Sub                              
                    private void timer1_Tick(object sender, EventArgs e) {     if (timeLeft > 0)     {         // Display the new time left         // by updating the Time Left label.         timeLeft = timeLeft - 1;         timeLabel.Text = timeLeft + " seconds";     }     else     {         // If the user ran out of time, stop the timer, show         // a MessageBox, and fill in the answers.         timer1.Stop();         timeLabel.Text = "Time's up!";         MessageBox.Show("You didn't finish in time.", "Sorry!");         sum.Value = addend1 + addend2;         startButton.Enabled = true;     } }                              

    Based on what you added, the timer checks each second whether time has run out by determining whether the timeLeft integer variable is greater than 0. If it is, time still remains. The timer first subtracts 1 from timeLeft and then updates the Text property of the timeLabel control to show the quiz taker how many seconds remain.

    If no time remains, the timer stops and changes the text of the timeLabel control so that it shows Time's up! A message box announces that the quiz is over, and the answer is revealed—in this case, by adding addend1 and addend2. The Enabled property of the startButton control is set to true so that the quiz taker can start another quiz.

    You just added an if else statement, which is how you tell programs to make decisions. An if else statement looks like the following.

    Note

    The following example is for demonstration only--don't add it to your project.

                    If (something that your program will check) Then     ' One or more statements that will run     ' if what the program checked is true. Else     ' One or more statements that will run     ' if what the program checked is false. End If                              
                    if (something that your program will check) {     // One or more statements that will run     // if what the program checked is true. } else {     // One or more statements that will run     // if what the program checked is false. }                              

    Look closely at the statement that you added in the else block to show the answer to the addition problem.

                    sum.Value = addend1 + addend2                              
                    sum.Value = addend1 + addend2;                              

    The statement addend1 + addend2 adds the values in the two variables together. The first part (sum.Value) uses the Value property of the sum NumericUpDown control to display the correct answer. You use the same property later to check the answers for the quiz.

    Quiz takers can enter numbers more easily by using a NumericUpDown control, which is why you use one for the answers to the math problems. All of the potential answers are whole numbers from 0 through 100. By leaving the default values of the Minimum, Maximum, and DecimalPlaces properties, you ensure that quiz takers can't enter decimals, negative numbers, or numbers that are too high. (If you wanted to allow quiz takers to enter 3.141 but not 3.1415, you could set the DecimalPlaces property to 3.)

  6. Add three lines to the end of the StartTheQuiz() method, so the code looks like the following.

                    ''' <summary> ''' Start the quiz by filling in all of the problem  ''' values and starting the timer.  ''' </summary> ''' <remarks></remarks> Public Sub StartTheQuiz()      ' Fill in the addition problem.     ' Generate two random numbers to add.     ' Store the values in the variables 'addend1' and 'addend2'.     addend1 = randomizer.Next(51)     addend2 = randomizer.Next(51)      ' Convert the two randomly generated numbers     ' into strings so that they can be displayed     ' in the label controls.     plusLeftLabel.Text = addend1.ToString()     plusRightLabel.Text = addend2.ToString()      ' 'sum' is the name of the NumericUpDown control.     ' This step makes sure its value is zero before     ' adding any values to it.     sum.Value = 0      ' Start the timer.     timeLeft = 30     timeLabel.Text = "30 seconds"     Timer1.Start()  End Sub                              
                    /// <summary> /// Start the quiz by filling in all of the problem  /// values and starting the timer.  /// </summary> public void StartTheQuiz() {     // Fill in the addition problem.     // Generate two random numbers to add.     // Store the values in the variables 'addend1' and 'addend2'.     addend1 = randomizer.Next(51);     addend2 = randomizer.Next(51);      // Convert the two randomly generated numbers     // into strings so that they can be displayed     // in the label controls.     plusLeftLabel.Text = addend1.ToString();     plusRightLabel.Text = addend2.ToString();       // 'sum' is the name of the NumericUpDown control.     // This step makes sure its value is zero before     // adding any values to it.     sum.Value = 0;      // Start the timer.     timeLeft = 30;     timeLabel.Text = "30 seconds";      timer1.Start(); }                              

    Now, when your quiz starts, the timeLeft variable is set to 30 and the Text property of the timeLabel control is set to 30 seconds. Then the Start() method of the Timer control starts the countdown. (The quiz doesn't check the answer yet—that comes next.)

  7. Save your program, run it, and then choose the Start button on the form.

    The timer starts to count down. When time runs out, the quiz ends, and the answer appears. The following illustration shows the quiz in progress.

    Math quiz in progress
    Math quiz in progress

To continue or review

  • To go to the next tutorial step, see Step 4: Add the CheckTheAnswer() method.

  • To return to the previous tutorial step, see Step 2: Create a random addition problem.