日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

Java版的防抖(debounce)和节流(throttle)

發布時間:2025/3/21 java 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java版的防抖(debounce)和节流(throttle) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

概念

防抖(debounce)

當持續觸發事件時,一定時間段內沒有再觸發事件,事件處理函數才會執行一次,如果設定時間到來之前,又觸發了事件,就重新開始延時

節流(throttle)

當持續觸發事件時,保證在一定時間內只調用一次事件處理函數,意思就是說,假設一個用戶一直觸發這個函數,且每次觸發小于既定值,函數節流會每隔這個時間調用一次

區別

防抖是將多次執行變為最后一次執行
節流是將多次執行變為每隔一段時間執行

Java實現

防抖(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);} }

節流(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();} }

節流(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();} }

總結

以上是生活随笔為你收集整理的Java版的防抖(debounce)和节流(throttle)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。