Skip to content

Commit

Permalink
Merge pull request #182 from streamich/useThrottle-fix
Browse files Browse the repository at this point in the history
fix: useThrottle discard intermediary calls
  • Loading branch information
streamich authored Mar 27, 2019
2 parents 2fce39c + 4fda5bb commit 0a53a56
Showing 1 changed file with 12 additions and 12 deletions.
24 changes: 12 additions & 12 deletions src/useThrottle.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,26 @@
import { useRef, useEffect } from 'react';
import { useRef, useEffect, useCallback } from 'react';

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

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

useEffect(() => {
let timeout
const diff = Date.now() - lastRan.current
clearTimeout(timeout.current);
const diff = Date.now() - lastRan.current;

if (diff >= ms) {
fn.apply(null, args);
lastRan.current = Date.now();
run();
} else {
timeout = setTimeout(() => {
fn.apply(null, args);
lastRan.current = Date.now();
}, ms - diff)
timeout.current = window.setTimeout(run, ms - diff);
}

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

0 comments on commit 0a53a56

Please sign in to comment.