Search code examples
ctimerreplit

How do I run a timer in C


I am making a trivia game and want to make a countdown timer where the person playing only has a certain time to answer the question. I am fairly new to C and am looking for a basic way to set a timer.


Solution

  • If you don't mind the person playing answering and being told they are too late, you could use something like this.

    time.h gives us the ability to track processor clocks to time. It also gives us some nifty functions like double difftime(time_t timer2, time_t timer1) which returns the difference between two timers in seconds.

    #include <stdio.h>
    #include <time.h>
    
    int main(void) {
      time_t start_time;
      time_t current_time;
    
      time(&start_time);
      time(&current_time);
      double delay = 5;
      int answer = 0;
      double diff = 0;
      while (diff < delay) {
        diff = difftime(current_time, start_time);
        scanf("%d", &answer);
        printf("Nope not %d\n", answer);
        time(&current_time);
      }
      printf("Too late\n");
      return 0;
    }
    

    The only problem is scanf will lock the program and a reply will haft to be given before the loop stops. If this isn't what you are looking for, then you should look into using threads. Which is OS dependent.