@deepkit/core
Version:
Deepkit core library
78 lines • 2.35 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.bufferedGate = exports.throttleTime = void 0;
function __assignType(fn, args) {
fn.__type = args;
return fn;
}
/*
* Deepkit Framework
* Copyright (C) 2021 Deepkit UG, Marc J. Schmidt
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the MIT License.
*
* You should have received a copy of the MIT License along with this program.
*/
function throttleTime(call, cps = 5) {
let last = Date.now();
let dirty = false;
let lastArgs = [];
let execution = false;
function tick() {
const now = Date.now();
if (!execution && now - last > 1000 / cps) {
execution = true;
call(...lastArgs);
dirty = false;
last = Date.now();
execution = false;
}
if (dirty) {
requestAnimationFrame(tick);
}
}
tick.__type = ['tick', 'P"/!'];
return __assignType((...args) => {
dirty = true;
lastArgs = args;
tick();
}, ['args', '', 'P"@2!"/"']);
}
exports.throttleTime = throttleTime;
throttleTime.__type = ['', 'call', 'cps', 'args', 'throttleTime', 'PP"/!2""2#P"@2$$/!/%'];
/**
* This functions returns a stack that is filled as long as the gate is not activated.
* Once activated all recorded calls go to given callback and subsequent calls go directly to given callback.
*/
function bufferedGate(callback) {
const q = [];
let activated = false;
const throttled = throttleTime(async () => {
if (q.length === 0)
return;
for (const t of q) {
const result = callback(t);
if (result instanceof Promise) {
await result;
}
}
//empty the queue
q.splice(0, q.length);
});
return {
activate: () => {
activated = true;
throttled();
},
call: __assignType((i) => {
q.push(i);
if (activated) {
throttled();
}
}, [() => callback, 'arg', '', 'i', 'PPdi!Ph"!2""/#qe!!!j2$"/#'])
};
}
exports.bufferedGate = bufferedGate;
bufferedGate.__type = ['arg', '', 'callback', 'bufferedGate', 'PP"2!"/"2#"/$'];
//# sourceMappingURL=reactive.js.map