[英]_.throttle implementation using RXJS observables
我是Rxjs Observables的新手,我需要使用Rxjs進行限制。
在下划線中,我們使用以下代碼行-
_.throttle(functionName, timespan, {trailing : true/false}).
請協助觀察者如何做到這一點。
看看RxJs中的樣本運算符
這是div上mousemove事件的簡單示例。
const source = document.getElementById('source'); Rx.Observable .fromEvent(source, 'mousemove') .sample(1000) .map(event => ({x: event.offsetX, y: event.offsetY})) .subscribe(console.log);
#source { width: 400px; height: 400px; background-color: grey; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.all.js"></script> <div id="source"></div>
如果要使用RxJS實現節流,則可以這樣進行:
function throttle(fn, delay) { const subject = new Rx.Subject(); subject .sample(delay) .subscribe(args => fn(...args)); return (...args) => subject.onNext(args); } const sourceBtn = document.getElementById('source'); const countSpan = document.getElementById('count'); let count = 0; sourceBtn.addEventListener('click', throttle(() => { count++; countSpan.innerHTML = count; }, 1000));
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.all.js"></script> <button id="source" type="button">click</button> <br> count = <span id="count"></span>
只需使用throttle
操作器即可。
Rx.Observable.fromEvent(window, 'mousemove')
.throttle(500)
.subscribe(x => console.log(x));
它將限制事件,以便在一個500毫秒的窗口內只能發生一個事件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.