/**
 * @since Last modified: 2024/05/23 14:44:37
 * @function throttle
 * @param {function} fn - Target function.
 * @param {number} [intvl=500]  - The intvl of throttle.Execute only once within this time.
 * @param {boolean} [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 ax from "../ax";

const throttle = (fn:any, intvl:number = ax.config.throttle, prevent:boolean = false) => {
    let last = 0,
        timer: any = null,
        handler: any = function (this: any, e: any) {
            let now = new Date().getTime();
            if (now - last > intvl) {
                if (timer) {
                    clearTimeout(timer);
                    timer = null;
                }
                fn.apply(this, arguments);
                last = now;
            } else {
                prevent ? (e.stopPropagation(), e.preventDefault()) : null;
            }
        }
    handler.cancel =  ()=> {
        clearTimeout(timer);
        timer = null;
    }
    return handler;
}
export default throttle;
