我是Rxjs观察点的新手,我需要使用Rxjs实现节流。
在下划线中,我们使用下面的代码行-
_.throttle(functionName, timespan, {trailing : true/false}).请帮助如何使用可观察对象来做到这一点。
发布于 2016-07-30 02:40:31
只需使用throttle运算符。
Rx.Observable.fromEvent(window, 'mousemove')
.throttle(500)
.subscribe(x => console.log(x));它将限制事件,以便在单个500毫秒窗口内只能通过一个事件。
发布于 2016-07-29 14:24:51
看看RxJ中的sample运算符
下面是在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>
https://stackoverflow.com/questions/38651479
复制相似问题