The reason why that happens is because both draw()
and keyPressed()
are run sequentially on a single thread. keyPressed()
is processed only as soon as draw()
finishes, which you noticed.
The reason it’s done that way is because else there could be some code problems, from little frustrations on what happens, to complex threading problems no sane programmer would want to deal with.
For example, let’s say that your draw()
is this:
void draw(){
println("New draw cycle");
if(b==2){ println("b==2"); }
delay(5000);
if(b==2){ println("b==2"); }
}
Notice that the first and third lines are exactly the same, both check if b==2
.
Now, if keyPressed()
would be processed instantly on a separate thread, both statements, even if they are run one after another, would produce different results.
In rare occasions it could be anticipated and intended, but else it could easily just cause a lot of headache as to why two identical if
statements, run one after another, with nothing between them that could change the result, give different results.
However, what you could do instead is to let draw()
run at full speed, and run the code inside of it not as often. For example, here’s your code, changed to produce the result you want it to:
int b=0; //You didn't define it in the original code
void setup() {
size(200, 200);
}
void keyPressed() {
if (keyCode == LEFT) { //Also you forgot {} brackets there!
b+=1;
print("\nkeyb="+b);
}
}
void draw() {
if(frameCount%300 == 0){ //5000 milliseconds is ~300 frames - this is true on every 300th frame.
print("\ndrawb="+b);
}
}