I want to create a program that when ever the user click on the start button, the program will sleep between 3 sec to 10 sec and then a button will appear to allow the user to click on that button, then the time will print out and tell the user how long it take in milliseconds for the user to click on the button.
I know that I need to use Thread.Sleep()
and Environment.TickCount()
The problem is I don't know how to make the program sleep random between 3-10 sec
Thank you for the answer. Everything is working however a tiny problem occur
The problem is the first label doesn't write out "Get ready…" but it sleep for 3-10 sec before it print out "Get ready…". What i want is that the program print out "Get ready…" and then go to sleep for 3-10 sec.
Here is the code:
//Starts the count
private void btnStart_Click(object sender, EventArgs e)
{
label1.Text = "Get ready...";
//Generate random sleeptime
Random waitTime = new Random();
seconds = waitTime.Next(3 * 1000, 11 * 1000);
//Put the thread to sleep
System.Threading.Thread.Sleep(seconds);
//Show the button
btnNow.Show();
label2.Text = "NOW!";
//Count the time in milliseconds
start = Environment.TickCount;
}
Best Answer
You have to use the Random class:
Have a look at the reference: http://msdn.microsoft.com/en-US/library/2dx6wyd4.aspx
Note that the first integer parameter is inclusive, while the second paramter is exclusive. So you have to use 11 and not 10. (If you want to exclude 10 seconds you have to change that of course to "10").
You can multiply this number with 1000 to get your milliseconds value and use Thread.Sleep with that value.