一个简单的选择是使用millis()手动跟踪时间。
您将使用两个变量:
- 一个存储经过的时间
- 一个存储您需要的等待/延迟时间
在 draw() 方法中,您将检查当前时间(以毫秒为单位)与先前存储的时间之间的差异是否大于(或等于)延迟。
如果是这样,这将提示您为给定的延迟做任何事情并更新存储的时间:
int time;
int wait = 1000;
void setup(){
time = millis();//store the current time
}
void draw(){
//check the difference between now and the previously stored time is greater than the wait interval
if(millis() - time >= wait){
println("tick");//if it is, do something
time = millis();//also update the stored time
}
}
这是屏幕上更新“针”的细微变化:
int time;
int wait = 1000;
boolean tick;
void setup(){
time = millis();//store the current time
smooth();
strokeWeight(3);
}
void draw(){
//check the difference between now and the previously stored time is greater than the wait interval
if(millis() - time >= wait){
tick = !tick;//if it is, do something
time = millis();//also update the stored time
}
//draw a visual cue
background(255);
line(50,10,tick ? 10 : 90,90);
}
根据您的设置/需要,您可以选择将此类内容包装到可以重用的类中。这是一种基本方法,也应该适用于 Android 和 JavaScript 版本(尽管在 javascript 中你有 setInterval())。
如果您对使用 Java 的实用程序感兴趣,正如 FrankieTheKneeMan 建议的那样,有一个TimerTask类可用,我相信那里有很多资源/示例。
您可以运行以下演示:
var time;
var wait = 1000;
var tick = false;
function setup(){
time = millis();//store the current time
smooth();
strokeWeight(3);
}
function draw(){
//check the difference between now and the previously stored time is greater than the wait interval
if(millis() - time >= wait){
tick = !tick;//if it is, do something
time = millis();//also update the stored time
}
//draw a visual cue
background(255);
line(50,10,tick ? 10 : 90,90);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.4/p5.min.js"></script>