Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
436 views
in Technique[技术] by (71.8m points)

javascript - What does RxJS.Observable debounce do?

Can anybody explain in plain English what RxJS Observable debounce function does?

I imagine it emits an event once in a while depending on the parameters, but my code below doesn't work as I expected.

var x$ = Rx.Observable.fromEvent(window, 'click')
    .map(function(e) {return {x:e.x, y:e.y};})
    .debounce(1000)
    .subscribe(function(el) {
      console.log(el);
    });

and the JsBin version.

I expected that this code would print one click once per second, no matter how fast I am clicking. Instead it prints the click at what I think are random intervals.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Debounce will emit a value after a specified time interval has passed without another value being emitted.

Using simple diagrams the following may provide greater help:

Stream 1 | ---1-------2-3-4-5---------6----

    after debounce, the emitted stream looks like as follows:

Stream 2 | ------1-------------5---------6-

The intermediate items (in this case, 2,3,4) are ignored.

An example is illustrated below:

var Rx = require('rx-node');
var source = Rx.fromStream(process.stdin).debounce(500);
var subscription = source.subscribe(
    function (x) {
        console.log('Next: %s', x);
    }
);

I used node to illustrate this... assuming you have node installed, you can run it by typing

$node myfile.js  (where the aforementioned code is in myfile.js)

Once this node program is started you can type values at the console -- if you type quickly items are ignored, and if type intermittently fast and slow items will appear after a gap in typing (in the example above I have 500ms) at the console ("Next: ")

There is also some excellent reference material at https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/debounce.md


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...