/** Limit function execution frequency. */
export function throttle(fn, period) {
    let timeout;
    let prev = 0;
    let nextArgs;
    return function (...args) {
        nextArgs = args;
        timeout ?? (timeout = globalThis.setTimeout(() => {
            prev = Date.now();
            timeout = undefined;
            const args = nextArgs;
            nextArgs = undefined;
            fn.apply(this, args);
        }, Math.max(0, period - (Date.now() - prev))));
        return () => {
            if (timeout != null)
                globalThis.clearTimeout(timeout);
            timeout = undefined;
            nextArgs = undefined;
        };
    };
}
