implementing debounce in Java

前端 未结 8 640
心在旅途
心在旅途 2020-11-30 04:09

For some code I\'m writing I could use a nice general implementation of debounce in Java.

public interface Callback {
  public void call(Object          


        
8条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 04:42

    I don't know if it exists but it should be simple to implement.

    class Debouncer implements Callback {
    
      private CallBack c;
      private volatile long lastCalled;
      private int interval;
    
      public Debouncer(Callback c, int interval) {
         //init fields
      }
    
      public void call(Object arg) { 
          if( lastCalled + interval < System.currentTimeMillis() ) {
            lastCalled = System.currentTimeMillis();
            c.call( arg );
          } 
      }
    }
    

    Of course this example oversimplifies it a bit, but this is more or less all you need. If you want to keep separate timeouts for different arguments, you'll need a Map instead of just a long to keep track of the last execution time.

提交回复
热议问题