Hi All,
I was just wondering if someone could explain to me how / why the code re-enters the timer1_Tick() method when counting down.
timeLeft = 30... It checks to see if timeLeft is greater than 0, OK... timeLeft = timeLeft minus 1,,, and then displays the new timeLeft value (29), OK...... I understand up to here!
Stepping through the code, it then jumps to the closing curly bracket of the timer1_Tick() method.... but then re-enters the method to repeat the process, which I know is what we want but why / how is it doing this if its not in a loop?
I would expect it to exit the method and only re-enter after being called again!
Thanks guys!
P.S. FYI Its the last method!
Code: Select all
namespace Math_Quiz
{
public partial class Form1 : Form
{
// Create a ramdom object to genterate random numbers.
Random randomizer = new Random();
// These ints will store the numbers for
// the adition problem
int addend1;
int addend2;
// This int will keep track of the time left.
int timeLeft;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
/// <summary>
/// Start the quiz by filling in all the problems
/// and starting the timer.
/// </summary>
private void startTheQuiz()
{
// Fill in the addition problems.
addend1 = randomizer.Next(51);
addend2 = randomizer.Next(51);
plusLeftLabel.Text = addend1.ToString();
plusRightLabel.Text = addend2.ToString();
sum.Value = 0;
//Start the timer
timeLeft = 30;
timeLabel.Text = "30 seconds";
timer1.Start();
}
private void startButton_Click(object sender, EventArgs e)
{
startTheQuiz();
startButton.Enabled = false;
}
private void timer1_Tick(object sender, EventArgs e)
{
if (timeLeft > 0)
{
// Display the new time left
// by updating the timeLeft label.
timeLeft = timeLeft - 1;
timeLabel.Text = timeLeft + " seconds";
}
else
{
// If the user runs out of time, stop the timer, show
// a MessageBox, and fill in the answer.
timer1.Stop();
timeLabel.Text = "Time's up!";
MessageBox.Show("You didn't finish in time.", "Sorry");
sum.Value = addend1 + addend2;
startButton.Enabled = true;
}
}
}
}