Created
June 13, 2018 20:11
-
-
Save alexnoz/0352bdd1b92ea2d50f7eddb890de71fe to your computer and use it in GitHub Desktop.
Abort fetching data in a function when debouncing it
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
function debounceFetch (fn, delay, onCancel = () => {}) { | |
let timer = 0, isFetching = false | |
return function (...args) { | |
clearTimeout(timer) | |
if (isFetching) { | |
onCancel() | |
isFetching = false | |
} | |
timer = setTimeout(() => { | |
isFetching = true | |
fn(...args) | |
}, delay) | |
} | |
} | |
function getAbortable () { | |
let controller | |
return { | |
fetch: (url, opts = {}) => { | |
controller = new AbortController() | |
return fetch(url, Object.assign({}, opts, { | |
signal: controller.signal | |
})) | |
}, | |
abort: () => controller.abort() | |
} | |
} | |
// Usage | |
const $input = document.querySelector('input') | |
const abortable = getAbortable() | |
$input.addEventListener('input', debounceFetch(handleInput, 250, abortable.abort)) | |
function handleInput ({ target: { value } }) { | |
abortable.fetch(`/api/search?q=${value}`) | |
.then(res => res.json()) | |
.then(console.log) | |
.catch(console.error) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment