Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useThrottle #154

Closed
gausie opened this issue Mar 22, 2019 · 4 comments
Closed

useThrottle #154

gausie opened this issue Mar 22, 2019 · 4 comments
Labels

Comments

@gausie
Copy link

gausie commented Mar 22, 2019

It would be nice to have useThrottle, implemented similarly to useDebounce

@streamich
Copy link
Owner

🎉 This issue has been resolved in version 6.1.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

@gausie
Copy link
Author

gausie commented Mar 27, 2019

@streamich unfortunately it's not implemented correctly - instead of discarding the intermediary function calls, it just delays them all.

i adapted this code as follows

import * as React from 'react';

export const useThrottle = (fn: () => any, ms: number = 0, args?: any) => {
  const lastRan = React.useRef(0);
  const timeout = React.useRef(0);

  const run = React.useCallback(() => {
    fn.apply(null, args);
    lastRan.current = Date.now();
  }, [lastRan, fn, args]);

  React.useEffect(() => {
    clearTimeout(timeout.current);

    const diff = Date.now() - lastRan.current;
    if (diff >= ms) {
      run();
    } else {
      timeout.current = setTimeout(run, ms - diff);
    }

    return () => { clearTimeout(timeout.current) }
  }, args);
};

@streamich
Copy link
Owner

@gausie thanks, I will add this fix

@streamich
Copy link
Owner

🎉 This issue has been resolved in version 6.2.2 🎉

The release is available on:

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants