/**
 * @since Last modified: 2024-08-06 10:47:55
 * @function debounce
 * @param {function} fn - Target function.
 * @param {number} [delay=200]  - The delay of debounce.The operation is invalid within this time.
 * @param {boolean} [prevent=false]  - Whether to prevent default events in debounce delay.
 * @returns {function} - Return handler function width cancel method.
 * @see {@link https://codepen.io/axui/pen/MWxybYR|demo @ codepen}
 * @example
 * elem.onclick = ax.debounce(()=>{console.log('ok')});
 * <!--return a handler function-->
 */
'use strict';
import ax from "../ax";
import isMobi from "./isMobi";
import throttle from "./throttle";
const debounce = (fn: any, delay = ax.config.debounce, prevent = false) => {
    if (isMobi) {
        return throttle(fn, delay, prevent);
    } else {
        let timer: any = null,
            handler: any = function (this: any, e: any) {
                prevent ? (e.stopPropagation(), e.preventDefault()) : null;
                timer ? clearTimeout(timer) : null;
                timer = setTimeout(() => {
                    fn.apply(this, arguments);
                }, delay);
            }
        handler.cancel = () => timer ? clearTimeout(timer) : null;
        return handler;
    }
}
export default debounce;
