ix
Version:
The Interactive Extensions for JavaScript
54 lines (52 loc) • 2.08 kB
JavaScript
import { __asyncGenerator, __asyncValues, __await } from "tslib";
import { AsyncIterableX } from '../asynciterablex.mjs';
import { wrapWithAbort } from './withabort.mjs';
import { throwIfAborted } from '../../aborterror.mjs';
/** @ignore */
export class ThrottleAsyncIterable extends AsyncIterableX {
constructor(source, time) {
super();
this._source = source;
this._time = time;
}
[Symbol.asyncIterator](signal) {
return __asyncGenerator(this, arguments, function* _a() {
var _b, e_1, _c, _d;
throwIfAborted(signal);
let currentTime;
let previousTime;
try {
for (var _e = true, _f = __asyncValues(wrapWithAbort(this._source, signal)), _g; _g = yield __await(_f.next()), _b = _g.done, !_b; _e = true) {
_d = _g.value;
_e = false;
const item = _d;
currentTime = Date.now();
if (!previousTime || currentTime - previousTime > this._time) {
previousTime = currentTime;
yield yield __await(item);
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (!_e && !_b && (_c = _f.return)) yield __await(_c.call(_f));
}
finally { if (e_1) throw e_1.error; }
}
});
}
}
/**
* Throttles the source async-iterable sequence so that it doesn't emit more than one value during the given timeframe.
*
* @template TSource The type of elements in the source sequence.
* @param {number} time The time in milliseconds to throttle the source sequence.
* @returns {MonoTypeOperatorAsyncFunction<TSource>} The source sequence throttled by the given timeframe.
*/
export function throttle(time) {
return function throttleOperatorFunction(source) {
return new ThrottleAsyncIterable(source, time);
};
}
//# sourceMappingURL=throttle.mjs.map