Skip to content

Instantly share code, notes, and snippets.

@matinrco
Created October 27, 2017 19:50
Show Gist options
  • Save matinrco/a03ddab55aefa914446b0a137918ebaf to your computer and use it in GitHub Desktop.
Save matinrco/a03ddab55aefa914446b0a137918ebaf to your computer and use it in GitHub Desktop.
Prevent click debouncing in react native
export function throttle(func, wait, ctx, immediate = true) {
let timeoutRefId;
let args;
let context;
let timestamp;
let result;
const later = () => {
const last = timestampNow() - timestamp;
if (last < wait && last >= 0) {
timeoutRefId = setTimeout(later, wait - last);
} else {
timeoutRefId = null;
if (!immediate) {
result = func.apply(context, args);
if (!timeoutRefId) context = args = null;
}
}
};
return () => {
context = ctx || this;
// eslint-disable-next-line prefer-rest-params
args = arguments;
timestamp = timestampNow();
const callNow = immediate && !timeoutRefId;
if (!timeoutRefId) timeoutRefId = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
context = args = null;
}
return result;
};
}
//Then inside the constructor of any component:
constructor(props) {
super(props);
this.onTapThrottled = throttle(this.onTapThrottled, 300, this);
}
onTapThrottled() {
// run everything once per tap
}
@matinrco
Copy link
Author

matinrco commented Oct 27, 2017

I used this comment from react native navigation issues.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment