2015-08-15 188 views

回答

1

对于基本的独立延迟系统,您使用两个变量(一个用于记录时间,另一个用于存储延迟量)。看看this post的帖子了解更多详情。如果你需要多次延迟,你会有多对这些变量。对于一个基本的设置它可能会起作用,但如果你有很多延迟,它会变得非常混乱,非常快。

如果有帮助,我就开始组建了一个基本的设置,以便您可以运行延迟一拉JavaScript的setTimeout()setInterval():这个想法是你叫的setTimeout,如果你想延迟一定时间后一个函数调用,传递的名字你的函数为一个字符串,在millieconds延迟:

color firstColor,secondColor,thirdColor; 
float rectWidth; 
void setup(){ 
    size(400,400); 
    noStroke(); 
    rectWidth = width/3.0; 

    setTimeout("onFirstDelay",1000); 
    setTimeout("onSecondDelay",1500); 
    setTimeout("onThirdDelay",1750); 
} 
void draw(){ 
    fill(firstColor); 
    rect(0,0,rectWidth,height); 

    fill(secondColor); 
    rect(rectWidth,0,rectWidth,height); 

    fill(thirdColor); 
    rect(rectWidth*2,0,rectWidth,height); 
} 

void onFirstDelay(){ 
    firstColor = color(192,0,0); 
} 
void onSecondDelay(){ 
    secondColor = color(0,192,0); 
} 
void onThirdDelay(){ 
    thirdColor = color(0,0,192); 
} 

//this code can be in a separate tab to keep things somewhat tidy 
void setTimeout(String name,long time){ 
    new TimeoutThread(this,name,time,false); 
} 
void setInterval(String name,long time){ 
    intervals.put(name,new TimeoutThread(this,name,time,true)); 
} 
void clearInterval(String name){ 
    TimeoutThread t = intervals.get(name); 
    if(t != null){ 
    t.kill(); 
    t = null; 
    intervals.put(name,null); 
    } 
} 
HashMap<String,TimeoutThread> intervals = new HashMap<String,TimeoutThread>(); 

import java.lang.reflect.Method; 

class TimeoutThread extends Thread{ 
    Method callback; 
    long now,timeout; 
    Object parent; 
    boolean running; 
    boolean loop; 

    TimeoutThread(Object parent,String callbackName,long time,boolean repeat){ 
    this.parent = parent; 
    try{ 
     callback = parent.getClass().getMethod(callbackName); 
    }catch(Exception e){ 
     e.printStackTrace(); 
    } 
    if(callback != null){ 
     timeout = time; 
     now = System.currentTimeMillis(); 
     running = true; 
     loop = repeat; 
     new Thread(this).start(); 
    } 
    } 

    public void run(){ 
    while(running){ 
     if(System.currentTimeMillis() - now >= timeout){ 
     try{ 
      callback.invoke(parent); 
     }catch(Exception e){ 
      e.printStackTrace(); 
     } 
     if(loop){ 
      now = System.currentTimeMillis(); 
     }else running = false; 
     } 
    } 
    } 
    void kill(){ 
    running = false; 
    } 

} 

通知的3个不同的矩形,在不同的延迟改变颜色。