throttle-debounce#throttle TypeScript Examples

The following examples show how to use throttle-debounce#throttle. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CosmosPortfolio.tsx    From anthem with Apache License 2.0 6 votes vote down vote up
constructor(props: IProps) {
    super(props);

    this.throttledPortfolioRedrawFunction = throttle(
      250,
      this.redrawPortfolioOnWindowChanges,
    );

    this.throttledPortfolioCalculationFunction = throttle(
      250,
      this.calculatePortfolioData,
    );

    const selectedDenom = getDefaultDenomFromNetwork(props.network);

    this.state = {
      selectedDenom,
      portfolioChartData: null,
    };
  }
Example #2
Source File: useEdges.ts    From react-datasheet-grid with MIT License 6 votes vote down vote up
useEdges = (
  ref: React.RefObject<HTMLElement>,
  width?: number,
  height?: number
) => {
  const [edges, setEdges] = useDeepEqualState({
    top: true,
    right: true,
    bottom: true,
    left: true,
  })

  useEffect(() => {
    const onScroll = throttle(100, () => {
      setEdges({
        top: ref.current?.scrollTop === 0,
        right:
          (ref.current?.scrollLeft ?? 0) >=
          (ref.current?.scrollWidth ?? 0) - (width ?? 0) - 1,
        bottom:
          (ref.current?.scrollTop ?? 0) >=
          (ref.current?.scrollHeight ?? 0) - (height ?? 0) - 1,
        left: ref.current?.scrollLeft === 0,
      })
    })

    const current = ref.current
    current?.addEventListener('scroll', onScroll)
    setTimeout(onScroll, 100)

    return () => {
      current?.removeEventListener('scroll', onScroll)
      onScroll.cancel()
    }
  }, [height, width, ref, setEdges])

  return edges
}
Example #3
Source File: useGetBoundingClientRect.ts    From react-datasheet-grid with MIT License 6 votes vote down vote up
useGetBoundingClientRect = (
  ref: RefObject<HTMLElement>,
  delay = 200
) => {
  const boundingRect = useRef<DOMRect | null>(null)

  const throttledCompute = useMemo(
    () =>
      throttle(delay, true, () => {
        setTimeout(
          () =>
            (boundingRect.current =
              ref.current?.getBoundingClientRect() || null),
          0
        )
      }),
    [ref, delay]
  )

  return useCallback(
    (force = false) => {
      if (force) {
        boundingRect.current = ref.current?.getBoundingClientRect() || null
      } else {
        throttledCompute()
      }
      return boundingRect.current
    },
    [ref, throttledCompute]
  )
}
Example #4
Source File: useLocalStorageSync.tsx    From amazon-chime-live-events with Apache License 2.0 6 votes vote down vote up
updateStorage = throttle(
  250,
  (key: string, value: string | object, ttl?: number) => {
    const ttlFromNow = ttl && Date.now() + ttl;
    const storedValue: StoredValue = {
      value,
      ttl: ttlFromNow,
    };
    localStorage.setItem(key, JSON.stringify(storedValue));
  }
)
Example #5
Source File: useScroll.ts    From vhook with MIT License 6 votes vote down vote up
export function useScroll(target: string | Element | Ref<Element | null>, delay = 200): IScrollResult {
  const x = ref(0)
  const y = ref(0)
  let cb = () => {
    if (eventTarget.value) {
      x.value = ((eventTarget.value as unknown) as Element).scrollLeft
      y.value = ((eventTarget.value as unknown) as Element).scrollTop
    }
  }
  if (delay) {
    cb = throttle(delay, cb)
  }
  const [eventTarget, clear] = useEvent('scroll', cb, { capture: false, passive: true }, target)
  return [readonly(x), readonly(y), clear]
}
Example #6
Source File: useWindowScroll.ts    From vhook with MIT License 6 votes vote down vote up
export function useWindowScroll(delay = 200): IWindowScrollState {
  const x = ref(isClient ? window.scrollX : 0)
  const y = ref(isClient ? window.scrollY : 0)
  let cb = () => {
    x.value = window.scrollX
    y.value = window.scrollY
  }
  if (delay) {
    cb = throttle(delay, cb)
  }
  const [, clear] = useEvent('scroll', cb, {
    passive: true,
    capture: false
  })
  return {
    x: readonly(x),
    y: readonly(y),
    clear
  }
}
Example #7
Source File: useWindowWidth.ts    From questdb.io with Apache License 2.0 6 votes vote down vote up
useWindowWidth = (): number | undefined => {
  const isClient = typeof window !== "undefined"

  const getWidth = () => {
    if (!isClient) {
      return undefined
    }

    return window.innerWidth
  }

  const [windowWidth, setWindowWidth] = useState(getWidth)

  useEffect(() => {
    if (!isClient) {
      return undefined
    }

    const handleResize = throttle(16, () => {
      setWindowWidth(getWidth())
    })

    window.addEventListener("resize", handleResize)
    return () => window.removeEventListener("resize", handleResize)
  }, [])

  return windowWidth
}
Example #8
Source File: Draggable.ts    From Cromwell with MIT License 5 votes vote down vote up
private tryToInsert = throttle(100, (event: MouseEvent) => {
        if (!this.hoveredBlock || !this.draggingBlock) return;
        if (this.draggingBlock.contains(this.hoveredBlock)) return;

        const afterElement = this.getDragAfterElement(this.hoveredBlock, event.clientY);

        const canInsert = this.canInsertBlock ?
            this.canInsertBlock(this.hoveredBlock, this.draggingBlock, afterElement) : true;

        if (canInsert) {
            let blockToInsert: HTMLElement | null = null;

            if (this.options.disableInsert) {
                blockToInsert = this.draggingBlockShadow;

                if (this.options.dragPlacement === 'element') {
                    this.draggingBlock.style.display = 'none';
                }

                if (this.draggingBlockShadow) this.draggingBlockShadow.style.display = '';
                this.lastInsertionData = {
                    draggingBlock: this.draggingBlock,
                    container: this.hoveredBlock,
                    afterElement: afterElement as HTMLElement
                }
            } else {
                blockToInsert = this.draggingBlock;
            }

            try {
                if (blockToInsert) {
                    if (afterElement) {
                        this.hoveredBlock.insertBefore(blockToInsert, afterElement)
                    } else {
                        this.hoveredBlock.appendChild(blockToInsert);
                    }
                }

                this.options?.onTryToInsert(this.hoveredBlock, this.draggingBlock, blockToInsert, afterElement)


                if (!this.options.disableInsert)
                    this.onBlockInserted?.(this.hoveredBlock, this.draggingBlock, afterElement);
            } catch (e) {
                console.error(e);
            }

        }
    });
Example #9
Source File: ui.ts    From monkeytype with GNU General Public License v3.0 5 votes vote down vote up
throttledEvent = throttle(250, () => {
  Caret.hide();
})
Example #10
Source File: index.tsx    From jobsgowhere with MIT License 4 votes vote down vote up
Header: React.FC = function () {
  const [mobileNavActive, setMobileNavActive] = React.useState(false);
  const toggleNav = function () {
    setMobileNavActive(!mobileNavActive);
  };
  const scrollRef = React.useRef(0);
  const [fixed, setFixed] = React.useState(false);
  const [hidden, setHidden] = React.useState(false);
  const [profileImage, setProfileImage] = React.useState<string>();

  const match = useRouteMatch<{ postId: string }>("/(jobs|talents)/:postId");
  const { isDetailView } = useMobileViewContext();
  const isDetailScreen = Boolean(match?.params?.postId && isDetailView);

  const auth0Context = React.useContext(Auth0Context);
  const isAuthenticated = auth0Context?.state.matches("authenticated") ?? false;
  const { profile } = useProfile();

  console.log(auth0Context?.state.value);

  auth0Context?.state.context.client?.getUser().then((user) => {
    if (user) setProfileImage(user.picture);
  });

  const handleLogin = () => {
    auth0Context?.send("LOGIN");
  };
  const handleLogout = () => {
    auth0Context?.send("LOGOUT");
  };

  const scrollHandler = React.useCallback(() => {
    const { scrollY } = window;

    setHidden(scrollY >= 56 && scrollY > scrollRef.current);

    // Forces repaint when [hidden] is changed and header is not fixed prior
    // This is to prevent unwanted transition when [hidden] and [fixed] are set to true in the same render
    if (!fixed) {
      // eslint-disable-next-line
      const _ = window.scrollY;
    }

    if (scrollY > 102) setFixed(true);
    if (scrollY === 0) setFixed(false);

    scrollRef.current = scrollY;
  }, [fixed]);

  React.useEffect(() => {
    const throttledScrollHandler = throttle(200, scrollHandler);
    window.addEventListener("scroll", throttledScrollHandler);
    return () => {
      window.removeEventListener("scroll", throttledScrollHandler);
    };
  }, [scrollHandler]);

  React.useEffect(() => {
    window.document.body.classList.toggle("mobile-scroll-lock", mobileNavActive);
  }, [mobileNavActive]);
  return (
    <>
      <Container
        className={`${fixed ? "fixed" : ""} ${
          isDetailScreen ? "fixed show" : hidden ? "hide" : "show"
        }`}
      >
        {isDetailScreen ? (
          <NavBack />
        ) : (
          <NavToggle onClick={toggleNav} active={mobileNavActive}>
            <i />
            <i />
            <i />
          </NavToggle>
        )}

        <Logo>
          <Link to="/">
            <img alt={process.env.REACT_APP_WEBSITE_NAME} src={LogoImg} />
          </Link>
        </Logo>
        <Nav>
          <UserNav
            isLoggedIn={isAuthenticated}
            isAuthorized={Boolean(profile)}
            handleLogin={handleLogin}
            handleLogout={handleLogout}
            profileImage={profileImage}
          />
        </Nav>
      </Container>
      <MobileNav
        active={mobileNavActive}
        setActive={setMobileNavActive}
        isLoggedIn={isAuthenticated}
        isAuthorized={Boolean(profile)}
        handleLogin={handleLogin}
        handleLogout={handleLogout}
        profileImage={profileImage}
      />
    </>
  );
}