From 15e6b322858b7555d97c7c5660a1ff33fda36473 Mon Sep 17 00:00:00 2001 From: chenshuai2144 Date: Wed, 8 Jan 2020 09:21:17 +0800 Subject: [PATCH 1/3] add debounce --- src/util.js | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/util.js diff --git a/src/util.js b/src/util.js new file mode 100644 index 0000000..2775b1c --- /dev/null +++ b/src/util.js @@ -0,0 +1,42 @@ +/* eslint-disable no-multi-assign */ +/* eslint-disable no-var */ +/* eslint-disable func-names */ +export const debounce = function(func, wait, immediate) { + // immediate默认为false + let timeout; + let args; + let context; + let timestamp; + let result; + + var later = function() { + const last = Date.now() - timestamp; + + if (last < wait && last >= 0) { + timeout = setTimeout(later, wait - last); + } else { + timeout = null; + if (!immediate) { + result = func.apply(context, args); + if (!timeout) context = args = null; + } + } + }; + + return function() { + context = this; + // eslint-disable-next-line prefer-rest-params + args = arguments; + timestamp = Date.now(); + // 第一次调用该方法时,且immediate为true,则调用func函数 + const callNow = immediate && !timeout; + // 在wait指定的时间间隔内首次调用该方法,则启动计时器定时调用func函数 + if (!timeout) timeout = setTimeout(later, wait); + if (callNow) { + result = func.apply(context, args); + context = args = null; + } + + return result; + }; +}; From d57b73055354a7f347c6ef437d916ad536fb4df0 Mon Sep 17 00:00:00 2001 From: chenshuai2144 Date: Wed, 8 Jan 2020 21:14:08 +0800 Subject: [PATCH 2/3] feat:finish waitTime --- examples/waitTime.tsx | 42 ++++++++++++++++++++++++++++++++++++++++ src/index.tsx | 10 ++++++++-- src/{util.js => util.ts} | 21 +++++++++++--------- 3 files changed, 62 insertions(+), 11 deletions(-) create mode 100644 examples/waitTime.tsx rename src/{util.js => util.ts} (68%) diff --git a/examples/waitTime.tsx b/examples/waitTime.tsx new file mode 100644 index 0000000..66033f8 --- /dev/null +++ b/examples/waitTime.tsx @@ -0,0 +1,42 @@ +import '../assets/index.less'; +import React from 'react'; +import ResizeObserver from '../src'; + +export default function App() { + const [times, setTimes] = React.useState(0); + const [disabled, setDisabled] = React.useState(false); + const textareaRef = React.useRef(null); + + React.useEffect(() => { + console.log('Ref:', textareaRef.current); + }, []); + + const onResize = ({ width, height }: { width: number; height: number }) => { + setTimes(prevTimes => prevTimes + 1); + console.log('Resize:', width, height); + }; + + return ( + +
+
+ + {' >>> '} + Resize times: {times} +
+ +