[英]_.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.