"use strict";
// https://codeburst.io/throttling-and-debouncing-in-javascript-b01cad5c8edf
Object.defineProperty(exports, "__esModule", { value: true });
exports.animateThrottle = exports.throttle = void 0;
const throttle = (system, func, limit) => {
    const { api: {}, } = system;
    let lastFunc;
    let lastRan;
    return function (...args) {
        const context = this;
        if (!lastRan) {
            func.apply(context, args);
            lastRan = Date.now();
        }
        else {
            clearTimeout(lastFunc);
            lastFunc = setTimeout(function () {
                if (Date.now() - lastRan >= limit) {
                    func.apply(context, args);
                    lastRan = Date.now();
                }
            }, limit - (Date.now() - lastRan));
        }
    };
};
exports.throttle = throttle;
const animateThrottle = (system, func) => {
    const { api: { animation: { requestAnimationFrame, cancelAnimationFrame }, }, } = system;
    let run = true;
    let frame;
    let run_last = false;
    const f = function (...args) {
        const context = this;
        if (run) {
            run = false;
            run_last = false;
            func.apply(context, args);
            frame = requestAnimationFrame(function () {
                run = true;
                if (run_last) {
                    run_last = false;
                    func.apply(context, args);
                }
            });
        }
        else {
            run_last = true;
        }
    };
    const abort = () => {
        if (frame !== undefined) {
            cancelAnimationFrame(frame);
            frame = undefined;
        }
    };
    return { f, abort };
};
exports.animateThrottle = animateThrottle;
//# sourceMappingURL=throttle.js.map