Question

I want to get the time between successive mouse clicks in ms. This is what I have tried:

void setup(){
  size(512,512);
  background(100,100,0);
}

void draw(){
}

void mousePressed(){
  println(new Date() - oldtime);
  var oldtime=new Date();
  }

The problem appears to be that processing.js does not remember the value of oldtime between calls to mousePressed().

On the first call, there has been no previous mouse click, oldtime is undefined, and the time should be NaN. But after the first click, oldtime is set, and so the above should work. I tried doing

var oldtime=new Date();

outside mousePressed() so that the first call would not be NaN, but no luck.

Thanks very much for any help.

===========================

The problem had to do with variable "scope". This works now

var oldtime=new Date();

void setup(){
  size(512,512);
  background(100,100,0);
}

void draw(){
}

void mousePressed(){
  println(new Date() - oldtime);
  oldtime=new Date();
  }
Was it helpful?

Solution

There is a built in method/function for this called millis(), no need to use the Date class. There is also no reason to call var. I would also initialize your classes and variables in the setup method. Here is how these changes would look in your code in processing syntax:

int oldtime;

void setup(){
  size(512,512);
  background(100,100,0);
  oldtime = millis()
}

void draw(){
}

void mousePressed(){
  println(millis() - oldtime);
  oldtime = millis()
}

If you are familiar with JavaScript you might find it beneficial use processing directly in javascript. That way it is easy to mix and match what you need and to use standard javascript debugging tools. There is a great tutorial on how to do this here:

http://processingjs.org/articles/jsQuickStart.html#javascriptonlyprocessingcode

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top