rxjs
Version:
Reactive Extensions for modern JavaScript
43 lines • 1.49 kB
JavaScript
import { asyncScheduler } from '../scheduler/async';
import { operate } from '../util/lift';
import { OperatorSubscriber } from './OperatorSubscriber';
export function debounceTime(dueTime, scheduler = asyncScheduler) {
return operate((source, subscriber) => {
let activeTask = null;
let lastValue = null;
let lastTime = null;
const emit = () => {
if (activeTask) {
activeTask.unsubscribe();
activeTask = null;
const value = lastValue;
lastValue = null;
subscriber.next(value);
}
};
function emitWhenIdle() {
const targetTime = lastTime + dueTime;
const now = scheduler.now();
if (now < targetTime) {
activeTask = this.schedule(undefined, targetTime - now);
subscriber.add(activeTask);
return;
}
emit();
}
source.subscribe(new OperatorSubscriber(subscriber, (value) => {
lastValue = value;
lastTime = scheduler.now();
if (!activeTask) {
activeTask = scheduler.schedule(emitWhenIdle, dueTime);
subscriber.add(activeTask);
}
}, () => {
emit();
subscriber.complete();
}, undefined, () => {
lastValue = activeTask = null;
}));
});
}
//# sourceMappingURL=debounceTime.js.map