Search code examples
xamarintimerxamarin.formsstopwatch

how to stop a stopwatch with a button click in Xamarin?


Goal is to measure the reaction time of the user. 3-10 seconds after clicking the start button it should start the stopwatch and make the stop button visible. After the user clicks the stop button, it should stop the watch and display the milliseconds the user took to respond.

I am having trouble coming up with a solution as to how to implement a loop that would check if the button has been pressed and to stop the watch without blocking the user from clicking the button.

public partial class Main : ContentPage
{

    public Main()
    {
        InitializeComponent();
    }
    public void OnStartClicked(object sender,EventArgs args)
    {
        Stopwatch stopWatch = new Stopwatch();
        startButton.IsVisible = false;
        BG.BackgroundColor = Color.Red;
        status_text.Text = "Get Ready";
        Random R = new Random();

         Device.StartTimer(TimeSpan.FromSeconds(R.Next(3, 10)), () =>
         {

             stopWatch.Start();
             stopButton.IsVisible = true;
             BG.BackgroundColor = Color.Green;


             long elapsed = stopWatch.ElapsedMilliseconds;
             stopWatch.Stop();
             status_text.Text = elapsed.ToString();
             return false;
         });
    }

}}

Solution

  • Use the StopWatch as a member Variable and stop the watch in an OnStopClicked-Event. Read the elapsed time after stopping. Instead of button.IsVisible you could also use button.IsEnabled.

    public partial class MainPage : ContentPage
    {
        Stopwatch mStopWatch = new Stopwatch();
    
        public MainPage()
        {
            InitializeComponent();
        }
    
        private void StartButton_Clicked(object sender, EventArgs e)
        {                       
            startButton.IsVisible = false;
            BG.BackgroundColor = Color.Red;
            status_text.Text = "Get Ready";
            Random R = new Random();
    
            Device.StartTimer(TimeSpan.FromSeconds(R.Next(3, 10)), () =>
            {
                mStopWatch.Start();
                stopButton.IsVisible = true;
                BG.BackgroundColor = Color.Green;                
                return false;
            });
        }
    
        private void StopButton_Clicked(object sender, EventArgs e)
        {
            mStopWatch.Stop();
            long elapsed = mStopWatch.ElapsedMilliseconds;            
            status_text.Text = elapsed.ToString();
            mStopWatch.Reset();
            stopButton.IsVisible = false;
            startButton.IsVisible = true;
        }
    }