UNPKG

ht_hooks

Version:
43 lines (42 loc) 1.39 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _tslib = require("tslib"); var _react = require("react"); var _useThrottleFn = _interopRequireDefault(require("../useThrottleFn")); function useThrottle(value, options) { var _a = (0, _tslib.__read)((0, _react.useState)(value), 2), throttled = _a[0], setThrottled = _a[1]; var run = (0, _useThrottleFn["default"])(function () { setThrottled(value); }, options).run; (0, _react.useEffect)(function () { run(); }, [value]); return throttled; } var _default = exports["default"] = useThrottle; // const useThrottle2=(callback:Callback,delay:number=500)=>{ // const throttleCallback=()=>{ // } // } function useThrottle3(fn, t) { var timer = null; (0, _react.useEffect)(function () { return function () { if (timer) clearTimeout(timer); }; }); return (0, _react.useCallback)(function () { if (!timer) { //#若timer有值说明正在计时中则什么都不做,若timer没值(计时结束定时器自动清除,timer手动清空)说明此时无计时,则开启定时,结束后执行然后关闭定时器 timer = setTimeout(function () { fn(); timer = null; }, t); } }, [timer, fn, t]); }