[d565449] | 1 | "use strict";
|
---|
| 2 | Object.defineProperty(exports, "__esModule", { value: true });
|
---|
| 3 | var tslib_1 = require("tslib");
|
---|
| 4 | var react_1 = require("react");
|
---|
| 5 | var useUnmount_1 = tslib_1.__importDefault(require("./useUnmount"));
|
---|
| 6 | var useThrottle = function (value, ms) {
|
---|
| 7 | if (ms === void 0) { ms = 200; }
|
---|
| 8 | var _a = react_1.useState(value), state = _a[0], setState = _a[1];
|
---|
| 9 | var timeout = react_1.useRef();
|
---|
| 10 | var nextValue = react_1.useRef(null);
|
---|
| 11 | var hasNextValue = react_1.useRef(0);
|
---|
| 12 | react_1.useEffect(function () {
|
---|
| 13 | if (!timeout.current) {
|
---|
| 14 | setState(value);
|
---|
| 15 | var timeoutCallback_1 = function () {
|
---|
| 16 | if (hasNextValue.current) {
|
---|
| 17 | hasNextValue.current = false;
|
---|
| 18 | setState(nextValue.current);
|
---|
| 19 | timeout.current = setTimeout(timeoutCallback_1, ms);
|
---|
| 20 | }
|
---|
| 21 | else {
|
---|
| 22 | timeout.current = undefined;
|
---|
| 23 | }
|
---|
| 24 | };
|
---|
| 25 | timeout.current = setTimeout(timeoutCallback_1, ms);
|
---|
| 26 | }
|
---|
| 27 | else {
|
---|
| 28 | nextValue.current = value;
|
---|
| 29 | hasNextValue.current = true;
|
---|
| 30 | }
|
---|
| 31 | }, [value]);
|
---|
| 32 | useUnmount_1.default(function () {
|
---|
| 33 | timeout.current && clearTimeout(timeout.current);
|
---|
| 34 | });
|
---|
| 35 | return state;
|
---|
| 36 | };
|
---|
| 37 | exports.default = useThrottle;
|
---|