Java版的防抖(debounce)和节流(throttle)
生活随笔
收集整理的這篇文章主要介紹了
Java版的防抖(debounce)和节流(throttle)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
概念
防抖(debounce)
當(dāng)持續(xù)觸發(fā)事件時,一定時間段內(nèi)沒有再觸發(fā)事件,事件處理函數(shù)才會執(zhí)行一次,如果設(shè)定時間到來之前,又觸發(fā)了事件,就重新開始延時
節(jié)流(throttle)
當(dāng)持續(xù)觸發(fā)事件時,保證在一定時間內(nèi)只調(diào)用一次事件處理函數(shù),意思就是說,假設(shè)一個用戶一直觸發(fā)這個函數(shù),且每次觸發(fā)小于既定值,函數(shù)節(jié)流會每隔這個時間調(diào)用一次
區(qū)別
防抖是將多次執(zhí)行變?yōu)樽詈笠淮螆?zhí)行
節(jié)流是將多次執(zhí)行變?yōu)槊扛粢欢螘r間執(zhí)行
Java實現(xiàn)
防抖(debounce)
public class DebounceTask {private Timer timer;private Long delay;private Runnable runnable;public DebounceTask(Runnable runnable, Long delay) {this.runnable = runnable;this.delay = delay;}public static DebounceTask build(Runnable runnable, Long delay){return new DebounceTask(runnable, delay);}public void run(){if(timer!=null){timer.cancel();}timer = new Timer();timer.schedule(new TimerTask() {@Overridepublic void run() {timer=null;runnable.run();}}, delay);} }節(jié)流(throttle)
public class ThrottleTask {private Timer timer;private Long delay;private Runnable runnable;private boolean needWait=false;public ThrottleTask(Runnable runnable, Long delay) {this.runnable = runnable;this.delay = delay;this.timer = new Timer();}public static ThrottleTask build(Runnable runnable, Long delay){return new ThrottleTask(runnable, delay);}public void run(){if(!needWait){needWait=true;timer.schedule(new TimerTask() {@Overridepublic void run() {needWait=false;runnable.run();}}, delay);}} }測試
防抖(debounce)
DebounceTask task = DebounceTask.build(new Runnable() {@Overridepublic void run() {System.out.println("do task: "+System.currentTimeMillis());} },1000L); long delay = 100; while (true){System.out.println("call task: "+System.currentTimeMillis());task.run();delay+=100;try {Thread.sleep(delay);} catch (InterruptedException e) {e.printStackTrace();} }節(jié)流(throttle)
ThrottleTask task = ThrottleTask.build(new Runnable() {@Overridepublic void run() {System.out.println("do task: "+System.currentTimeMillis());} },1000L); while (true){System.out.println("call task: "+System.currentTimeMillis());task.run();try {Thread.sleep(200);} catch (InterruptedException e) {e.printStackTrace();} }總結(jié)
以上是生活随笔為你收集整理的Java版的防抖(debounce)和节流(throttle)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java 防抖动函数的实现
- 下一篇: @Transactional事务的使用和