# A timer which activates by pressing a button

**URL:** https://discourse.processing.org/t/a-timer-which-activates-by-pressing-a-button/25818
**Category:** Coding Questions
**Created:** [November 29, 2020, 8:52pm UTC](https://discourse.processing.org/t/a-timer-which-activates-by-pressing-a-button/25818 "2020-11-29T20:52:44Z")
**Posts on this page:** 1
**Showing post:** 2

<div class="post-metadata">

### Author: ![josephh](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/josephh/32/210_2.png) [@josephh](https://discourse.processing.org/u/josephh)
#### Post date: [November 29, 2020, 11:20pm UTC](https://discourse.processing.org/t/a-timer-which-activates-by-pressing-a-button/25818/2 "2020-11-29T23:20:42Z")

</div>

Hi,

You were right, you need to use the `millis()` function. It’s true that it’s counting the number of milliseconds from the beginning of the execution but if we store that value when we press a button, it’s the same as taking the current time.

Think of it as a watch. If you want to measure the duration of an event, you look at the time on your watch then wait until the end of the event. At that time, you look at your watch and compute the difference in time.

Here is an example :

```auto
// The duration of the timer
int timerDuration = 2000;

// The time at which we start the timer
int startTime = 0;

// Whether or not the timer was started
boolean timerStarted = false;

void setup() {
  size(200, 200);
}

void draw() {
  background(255);
  
  if (timerStarted) {
    // We subtract the current time and the time when we started the timer
    int currentDuration = millis() - startTime;
    
    fill(0);
    textAlign(CENTER, CENTER);
    text(currentDuration, width / 2, height / 2);
    
    // If the event is over
    if (currentDuration > timerDuration) {
      timerStarted = false;
    }
  }
}

// When the mouse is pressed, take the current time and store it
void mousePressed() {
  startTime = millis();
  timerStarted = true;
}

```

---

_[View the full topic](https://discourse.processing.org/t/a-timer-which-activates-by-pressing-a-button/25818)._
