对于我正在编写的一些代码,我可以debounce在Java中使用一个很好的通用实现.
public interface Callback {
public void call(Object arg);
}
class Debouncer implements Callback {
public Debouncer(Callback c, int interval) { ... }
public void call(Object arg) {
// should forward calls with the same arguments to the callback c
// but batch multiple calls inside `interval` to a single one
}
}
Run Code Online (Sandbox Code Playgroud)
当使用相同的参数call()多次以interval毫秒为单位调用时,应该只调用一次回调函数.
可视化:
Debouncer#call xxx x xxxxxxx xxxxxxxxxxxxxxx
Callback#call x x x (interval is 2)
Run Code Online (Sandbox Code Playgroud)