Skip to content

Instantly share code, notes, and snippets.

@Calvin-Huang
Created September 6, 2017 03:06
Show Gist options
  • Save Calvin-Huang/6372b6147c45aeb15015259f92ec5050 to your computer and use it in GitHub Desktop.
Save Calvin-Huang/6372b6147c45aeb15015259f92ec5050 to your computer and use it in GitHub Desktop.
// Throttling
function* handleInput(input) {
// ...
}
function* watchInput() {
yield throttle(500, 'INPUT_CHANGED', handleInput)
}
// Debouncing
function* handleInput(input) {
// debounce by 500ms
yield call(delay, 500)
...
}
function* watchInput() {
let task
while (true) {
const { input } = yield take('INPUT_CHANGED')
if (task) {
yield cancel(task)
}
task = yield fork(handleInput, input)
}
}
// Debouncing written by takeLatest
function* handleInput({ input }) {
// debounce by 500ms
yield call(delay, 500)
...
}
function* watchInput() {
// will cancel current running handleInput task
yield takeLatest('INPUT_CHANGED', handleInput);
}
// Retry 5 times
function* updateApi(data) {
for(let i = 0; i < 5; i++) {
try {
const apiResponse = yield call(apiRequest, { data });
return apiResponse;
} catch(err) {
if(i < 4) {
yield call(delay, 2000);
}
}
}
// attempts failed after 5 attempts
throw new Error('API request failed');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment