timeprocessingrecordkeypresskeyrelease

Record time a key is held in Processing


I've searched on so many forums including this one and I can't see to find any answer for this. Many of the solutions given to me looked like this:

void keyPressed(){
  if (key == 'e'){
    t = millis();
  }
}

void keyReleased(){
   if (key == 'e'){
    t = millis()-t;
    println(t);
   }  
}

This is incorrect however because the keyPressed function continuously calls upon millis() when I hold a key. So when the key is released the recorded time prints a number close to zero!

How do I make keyPressed call millis() only once?


Solution

  • You could just use a boolean that tracks whether you've already set the value. Something like this:

    boolean recorded = false;
    
    void keyPressed(){
      if (key == 'e' && !recorded){
        t = millis();
        recorded = true;
      }
    }