implementing debounce in Java

前端 未结 8 690
心在旅途
心在旅途 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:44

    This looks like it could work:

    class Debouncer implements Callback {
        private Callback callback;
        private Map scheduled = new HashMap();
        private int delay;
    
        public Debouncer(Callback c, int delay) {
            this.callback = c;
            this.delay = delay;
        }
    
        public void call(final Object arg) {
            final int h = arg.hashCode();
            Timer task = scheduled.remove(h);
            if (task != null) { task.cancel(); }
    
            task = new Timer();
            scheduled.put(h, task);
    
            task.schedule(new TimerTask() {
                @Override
                public void run() {
                    callback.call(arg);
                    scheduled.remove(h);
                }
            }, this.delay);
        }
    }
    

提交回复
热议问题