Created
October 27, 2017 19:50
-
-
Save matinrco/a03ddab55aefa914446b0a137918ebaf to your computer and use it in GitHub Desktop.
Prevent click debouncing in react native
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I used this comment from react native navigation issues.