Advertisement
orgicus

setTimeout setInterval in Processing

May 7th, 2015
520
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.64 KB | None | 0 0
  1. float bg;
  2.  
  3. void setup(){
  4.   setTimeout("test",5000);
  5.   setInterval("tick",1000);
  6. }
  7. void draw(){
  8.   background(bg);
  9. }
  10. void test(){
  11.   println("test");
  12. }
  13. void tick(){
  14.   bg = random(255);
  15. }
  16. void mouseReleased(){
  17.   clearInterval("tick");
  18. }
  19.  
  20. void setTimeout(String name,long time){
  21.   new TimeoutThread(this,name,time,false);
  22. }
  23. void setInterval(String name,long time){
  24.   intervals.put(name,new TimeoutThread(this,name,time,true));
  25. }
  26. void clearInterval(String name){
  27.   TimeoutThread t = intervals.get(name);
  28.   if(t != null){
  29.     t.kill();
  30.     t = null;
  31.     intervals.put(name,null);
  32.   }
  33. }
  34. HashMap<String,TimeoutThread> intervals = new HashMap<String,TimeoutThread>();
  35.  
  36. import java.lang.reflect.Method;
  37.  
  38. class TimeoutThread extends Thread{
  39.   Method callback;
  40.   long now,timeout;
  41.   Object parent;
  42.   boolean running;
  43.   boolean loop;
  44.  
  45.   TimeoutThread(Object parent,String callbackName,long time,boolean repeat){
  46.     this.parent = parent;
  47.     try{
  48.       callback = parent.getClass().getMethod(callbackName);
  49.     }catch(Exception e){
  50.       e.printStackTrace();
  51.     }
  52.     if(callback != null){
  53.       timeout = time;
  54.       now = System.currentTimeMillis();
  55.       running = true;  
  56.       loop = repeat;
  57.       new Thread(this).start();
  58.     }
  59.   }
  60.  
  61.   public void run(){
  62.     while(running){
  63.       if(System.currentTimeMillis() - now >= timeout){
  64.         try{
  65.           callback.invoke(parent);
  66.         }catch(Exception e){
  67.           e.printStackTrace();
  68.         }
  69.         if(loop){
  70.           now = System.currentTimeMillis();
  71.         }else running = false;
  72.       }
  73.     }
  74.   }
  75.   void kill(){
  76.     running = false;
  77.   }
  78.  
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement