/**
 * @since Last modified: 2024-09-10 09:46:00
 * @function throttle
 * @param {function} fn - Target function.
 * @param {object|null|undefined|number} [options] - Parameters.If the parameter is a standard object, it should be merged with the default value; if it is a number, it represents the delay value; in other cases, it defaults to the standard parameters.
 * @param {number} [options.intvl=500]  - The intvl of throttle.Execute only once within this time.
 * @param {boolean} [options.prevent=false]  - Whether to prevent default events in throttle delay.
 * @returns {function} - Return handler function width cancel method.
 * @see {@link https://codepen.io/axui/pen/YzgqNmm|demo @ codepen}
 * @example
 * elem.onclick = ax.throttle(()=>{console.log('ok')});
 * <!--return a handler function-->
 */
'use strict';
import config from "../global/config";
import stdParam from "./stdParam";
const throttle = (fn, options) => {
    let dft = { intvl: config.throttle, prevent: false }, opts = stdParam(options, dft, 'intvl');
    let last = 0, timer = null, handler = function (e) {
        let now = Date.now();
        if (now - last > opts.intvl) {
            if (timer) {
                clearTimeout(timer);
                timer = null;
            }
            fn.apply(this, arguments);
            last = now;
        }
        else {
            opts.prevent ? (e.stopPropagation(), e.preventDefault()) : null;
        }
    };
    handler.cancel = () => {
        clearTimeout(timer);
        timer = null;
        return handler;
    };
    return handler;
};
export default throttle;
